Printing arrays with objects in Java - arrays

First, I made a copy of the deck of cards. Then, I tried to use a method I created to print only the first seven cards of that copy deck (which I need to do 2 times). nextCard is a counter to keep track of where we are in the deck.
Here is my class:public class Deck
{
private Card[] deck;
private int nextCard;
public Deck(){
deck = new Card[53];
nextCard = 0;
for(int i = 0; i < 52; i++){
deck[i] = new Card(i);
nextCard++;
}
}//Deck
public Deck(Deck existingDeck){//copy
this.deck = new Card[52];
for(int i=0; i < 52; i++){
this.deck[i] = new Card(existingDeck.deck[i]);
}
nextCard++;
}
public void shuffle(){
Card crdTemp = new Card();
Random random = new Random();
int num;
nextCard = 0;
for(int i = 0; i < 52; i++){
num = random.nextInt (51);
crdTemp = deck[i];
deck[i] = deck[num];
deck[num] = crdTemp;
nextCard++;
}
}
public Card dealACard(){
Card crd = null;
if(nextCard > -1){
crd = deck[nextCard];
nextCard--;
}
return crd;
}
public String dealAHand(int handSize){
Card crd = null;
String cards = "";
for(int i = 0; i < handSize; i++){
crd = dealACard();
cards += crd.toString();
//cards += dealACard().toString();
}
return cards;
}
public String toString(){
String info = "";
for(int i = 0; i < 52; i++){
deck[i].toString ( );
info += deck[i];
nextCard++;
}
return info;
}
}
Then, in my driver:
Deck bDeck = new Deck(aDeck);
bDeck.toString();
String[] sevenCards = new String[bDeck];
for(int i = 0; i < 7; i++){
System.out.println ("Copy deck: ");
sevenCards[i] = bDeck.toString();
}
for(int i = 0; i < 7; i++){
System.out.println (sevenCards[i]);
}
}
I assume I am assigning the entire bDeck to each sevenCards array element, but I don't know how to do it differently. I also assume there is a way to do it without trying to create a new array like this, but again, I've gone through a lot of different ideas and nothing has panned out. Would really appreciate some direction, thanks.

If I do understand you correctly, you want to print only the first seven cards of your deck? So you have to access the decks cards to do so:
Deck bDeck = new Deck(aDeck);
bDeck.toString();
String[] sevenCards = new String[7];
for(int i = 0; i < 7; i++){
System.out.println ("Copy deck: ");
sevenCards[i] = bDeck.deck[i];
}
for(int i = 0; i < 7; i++){
System.out.println (sevenCards[i]);
}
}
This will work if Deck.deck is accessible in your for loop and you properly implemented the toString() method of your Card class.
EDIT: Here are the final changes to dealACard():
public Card dealACard(){
Card crd = null;
if(nextCard > 0) {
nextCard--;
crd = deck[nextCard];
}
return crd;
}

Related

Need help on solving this Arrays problem using java

Make an array of integer (score) with 10 members. Randomize the
content with value between 0-100. For each of the member of array,
visualize the value using “-” for each ten. For example: score[0] = 55 will be visualized as “-----" (Using Java).
public class w9lab1 {
public static void main(String args[]) {
double[] temperature = new double[7];
for (int i = 0; i < 7; i++) {
temperature[i] = Math.random()*100;
}
for (int i = 0; i < 7; i++) {
System.out.println(temperature[i]);
}
double totalTemperature = 0;
for (int i = 0; i < 7 ; i++) {
totalTemperature += temperature[i];
}
double maxTemperature = temperature[0];
for (int i = 1; i < 7; i++){
if (temperature[i] > maxTemperature){
maxTemperature = temperature[i];
}
}
System.out.println("Temperatur maximum adalah " + maxTemperature);
}
}
import java.util.Random;
import java.util.Arrays;
public class w9lab1 {
public static void main(String[] args) {
Random random = new Random();
int[] score = new int[10];
for (int i = 0; i < score.length; i++) {
score[i] = random.nextInt(101);
for (int n = 1; n <= score[i] / 10; n++)
System.out.print('-');
System.out.println();
}
System.out.println(Arrays.toString(score));
}
}

2d array of type Space

I'm trying to make a 9x9 grid of Spaces with 1-10 int values. I'm using the java n-ide app, and am getting a successful compilation, but it's not printing any values.
class Space {
int one = 1;
int two = 2;
...
int ten = 10;
}
class green {
Space[][] board = new Space[9][9];
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = new Space();
System.out.println(board[i][j].one);
}
}
}
I think you can just refactor your Space class to just hold a primitive integer value:
class Space {
private int value;
private static final String MSG = "Space values must be between 1 and 10 inclusive";
public Space() { }
public Space(int value) {
// prevent spaces from being created with illegal values
if (value < 1 || value > 10) {
throw new IllegalArgumentException(MSG);
}
this.value = value;
}
public int getValue() {
return value;
}
}
Then, in your consuming class, use the Space class:
class Green {
private Space[][] board = new Space[9][9];
for (int i=0; i < board.length; i++) {
for (int j=0; j < board[i].length; j++) {
// maybe get a value from somewhere and use it below
board[i][j] = new Space();
}
}
}
Regarding your exact question about values not printing, the bigger problem than above is that you don't have any logic for assigning values.

gridview dataitem to decimal array

enter code hereHello I try to convert the dataitem into decimal array, here is my code;
if (e.Row.RowType == DataControlRowType.DataRow)
{
for (; i < 9; )
{
if (!DBNull.Value.Equals(DataBinder.Eval(e.Row.DataItem, headerNames[i])))
TotalSales += Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, headerNames[i]));
totals(e.Row.DataItem);
}
}
}
public static decimal[] totals(object arr)
{
decimal[] res = arr as decimal[];
decimal[] sRes = res.OfType<decimal>().ToArray();
return sRes;
}
I can see that the dataitem successfully assigned to arr.
However the line
decimal[] res = arr as decimal[]; does not assign the arr to res, so the next line gives me an error complaining the value cannot be null.
Can you please help?
While I was waiting for an answer here, I tried and came up with a code that calculates totals in GridView_DataBound event, please comment if there is anything can be better and how to not show the total (0.0) under the columns that do not have decimal values (i.e. string)
public static void gridViewTotals1(object sender , EventArgs e)
{
var grdview = (GridView)sender;
decimal[,] rowAndColumns = new decimal[grdview.Rows.Count, grdview.Columns.Count];
decimal n;
decimal[] totalSalesArray = new decimal[grdview.Columns.Count];
for (int i = 0; i < grdview.Columns.Count; i++)
{
for (int j = 0; j < grdview.Rows.Count; j++)
if (decimal.TryParse(grdview.Rows[j].Cells[i].Text, out n))
{
rowAndColumns[j, i] = Convert.ToDecimal(grdview.Rows[j].Cells[i].Text);
}
}
GridViewRow footerRow = grdview.FooterRow;
for (int k = 0; k < grdview.Columns.Count; k++)
{
decimal totalSales = 0;
for (int l = 0; l < grdview.Rows.Count; l++)
{
totalSales += rowAndColumns[l, k];
totalSalesArray[k] = totalSales;
footerRow.Cells[k].Text = String.Format("{0:N2}", totalSales);
}
}
}

Array index out of bounds in sieve of eratosthenes

I am having trouble with ArrayIndexOutOfBounds.
I am new to coding and I don't fully understand this problem and I am unable to fix it. Any help is appreciated.
public class Primes {
public static void main(String[] args) {
final int SIZE = 10000;
boolean[] numberIsPrime = new boolean[SIZE];
int rowCounter = 0;
for( int index = 1; index <= SIZE; index++) {
numberIsPrime[index] = true;
}
for( int index = 2; index <= SIZE; index++) {
if( numberIsPrime[index] = true){
for( int i = index; i <= SIZE; i++){
numberIsPrime[index * i] = false;
}
}
}
for( int index = 1; index <= SIZE; index++){
if( numberIsPrime[index] = true){
System.out.println(index + " ");
rowCounter++;
if( rowCounter == 10){
System.out.println();
}
}
}
}
}
You should tag the question with the language you're using, but I'm gonna assume it's Java. The problem is
boolean[] numberIsPrime = new boolean[SIZE];
...
for( int index = 1; index <= SIZE; index++) {
numberIsPrime[index] = true;
}
The first line declares numberIsPrime as an array of size 10000. That means you can access numberIsPrime[0], numberIsPrime[1], ... numberIsPrime[9999]. You can't access numberIsPrime[10000].

For loop error in Blackjack game

Can someone please explain to me why I am getting an error on line 20?
package play;
import java.security.SecureRandom;
public class Deck
{
private int cardsInDeck; //number of cards left in the deck
private Card[] deck; //the cards that are in the deck
private static final SecureRandom random = new SecureRandom();
public Deck()
{
deck = new Card[52]; //52 cards in a deck
int cardsUsed = 0;
for(int s = 0; s < 4; s++); //suit of card
{
for(int n = 1; n <= 13; n++) //number of card
{
deck[cardsUsed] = new Card(n, s); **error is "s" on this line**
cardsUsed++;
}
}
cardsInDeck = 0;
}
public void shuffle()
{
for(int shuff = 51; shuff > 0; shuff--)
{
//select random # between 0 and 51
int second = random.nextInt(52);
//swap current card with new random card
Card temp = deck[shuff];
deck[shuff] = deck[second];
deck[second] = temp;
}
cardsInDeck = 0;
}
public int remainingCards()
{
//number of cards decrease as they are dealt.
return 52 - cardsInDeck;
}
public Card dealCard()
{
//deals a card from the deck
if(cardsInDeck == 52)
shuffle();
cardsInDeck++;
return deck[cardsInDeck - 1];
}
}//end class Deck
Look closer
for(int s = 0; s < 4; s++); //suit of card
{
...
}
This semicolon causes that the variable s to not declared in the block below, that's why the error happens a few lines below.

Resources