Return statement in a toString class - java

So I have a Card class that looks like this:
public class Card
{
//instance variables
private String faceValue; //the face value of the card
private String suit; //the suit of the card
String[] ranks = {"Ace", "2", "3", "4", "5", "6","7", "8", "9", "10", "Jack", "Queen", "King"};
String[] suits = {"Clubs", "Diamonds", "Hearts", "Spades"};
/**
* Constructor
*/
public Card(int aValue, int aSuit)
{
faceValue = ranks[aValue];
suit = suits[aSuit];
}
//getters
/**
* Getter for faceValue.
*/
public String getFaceValue()
{
return faceValue;
}
/**
* Getter for suit.
*/
public String getSuit()
{
return suit;
}
//end of getters
//methods
/**
* This method returns a String representation of a Card object.
*
* #param none
* #return String
*/
public String toString()
{
return "A card: " + faceValue + " of " + suit;
}
}
And a Deck class that looks like this:
public class Deck
{
//instance variables
private Card[] deck;
/**
* Constructor for objects of class Deck
*/
public Deck()
{
deck = new Card[52];
int cardCount = 0; //number of cards created so far.
for (int aSuit = 0; aSuit < 4; aSuit++ )
{
for ( int aValue = 0; aValue < 13; aValue++ ) {
deck[cardCount] = new Test(aValue, aSuit);
cardCount++;
}
}
}
/**
* String representation.
*/
public String toString()
{
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
return "Dealt a card: " + v + " of " + s + ".";
}
}
}
My toString method in the deck shows an error "missing return statement". How do change the return statement while still allowing it to print the card details after every loop?

Code you wrote will only return 0th element from deck array. it should be like:
public String toString()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
sb.append("Dealt a card: ").append(v).append(" of ").append(s).append(".\n");
}
return sb.toString();
}

The error is because your toString method has the return type String.
Java checks for execution paths. What if the for loop ends and never returns anything?
Although you may have hardcoded that logic, but Java compiler does not do a statistical analysis of that. Hence it must return a type String which is sure to execute if nothing else works.
This will work:
public String toString()
{
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
return "Dealt a card: " + v + " of " + s + ".";
}
return "";
}
But I guess what you want is this:
public String toString()
{
StringBuilder returnValue = new StringBuilder("");
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
returnValue.append("Dealt a card: " + v + " of " + s + ".");
}
return returnValue.toString();
}

if u just want to print all the cards infos, u can use
public String toString(){
for (int i = 0; i < 52; i++)
{
String v = deck[i].getFaceValue();
String s = deck[i].getSuit();
System.out.println( "Dealt a card: " + v + " of " + s + ".");
}
return null;
}

Related

Deck of Cards - checking for a straight

I've made this poker program. It evaluates the hand and returns the results.
Everything works except my method to check for a straight. There is no error, but the method never returns true.
As a test, I have a while loop on the main (DeckOfCardsTest) to rerun the program until a straight is found.
Here is the code:
public class DeckOfCardsTest {
public static Card[] hand = new Card[5];
public static void main(String[] args) {
while(DeckOfCards.str == 0){
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print the hand dealt
for (int i = 0; i < 5; i++) {
// deal and display a Card
//System.out.printf("%-19s%n", myDeckOfCards.dealCard());
hand[i]= myDeckOfCards.dealCard();
if (i % 5 == 0) { // output a newline after every fifth card, incase dealing 2 hands in the future
System.out.println();
}
}//end of for loop
for(int i = 0; i < hand.length; i++){
System.out.println(""+ hand[i]);
}
DeckOfCards.Pair();//check hand for pair, 2 pair, 3 of a kind, four of a kind, or a full house
DeckOfCards.hasFlush(hand);//check hand for flush
System.out.println("\n\n\t" + DeckOfCards.Results() + "\n\n " + DeckOfCards.str);
//System.out.println(""+DeckOfCards.hasStraight(hand));
DeckOfCards.flushn=0;
}
} //end of main
}//end of class
Card Class
public class Card {
private final String face; // face of card ("Ace", "Deuce", ...)
private final String suit; // suit of card ("Hearts", "Diamonds", ...)
// two-argument constructor initializes card's face and suit
public Card(String cardFace, String cardSuit) {
this.face = cardFace; // initialize face of card
this.suit = cardSuit; // initialize suit of card
} //end of Card inilization
// return String representation of Card
public String toString() {
return face + " of " + suit;
}// endof toString method
public String getFace() {
return face;
}//end of getFace method
public String getSuit() {
return suit;
}//end of getSuit method
}//end of Class
Deck class
import java.security.SecureRandom;
public class DeckOfCards {
// random number generator
private static final SecureRandom randomNumbers = new SecureRandom();
private static final int NUMBER_OF_CARDS = 52; // constant # of Cards
public static int flushn = 0;
public static int str=0;
//private Card[] hand;
private Card[] deck = new Card[NUMBER_OF_CARDS]; // Card references
private int currentCard = 0; // index of next Card to be dealt (0-51)
// constructor fills deck of Cards
public DeckOfCards() {
String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
String[] suits = {"Hearts", "Diamonds", "Clubs", "Spades"};
// populate deck with Card objects
for (int count = 0; count < deck.length; count++) {
deck[count] =
new Card(faces[count % 13], suits[count / 13]);
}
} //end of DeckOfCards constructor
public String getCard(){
String cCard = ("");
return cCard;
}
// shuffle deck of Cards with one-pass algorithm
public void shuffle() {
// next call to method dealCard should start at deck[0] again
currentCard = 0;
// for each Card, pick another random Card (0-51) and swap them
for (int first = 0; first < deck.length; first++) {
// select a random number between 0 and 51
int second = randomNumbers.nextInt(NUMBER_OF_CARDS);
// swap current Card with randomly selected Card
Card temp = deck[first];
deck[first] = deck[second];
deck[second] = temp;
}
} //end of shuffle method
// deal one Card
public Card dealCard() {
// determine whether Cards remain to be dealt
if (currentCard < deck.length) {
return deck[currentCard++]; // return current Card in array
}
else {
return null; // return null to indicate that all Cards were dealt
}
}//end of dealCard method
public static void hasFlush(Card[] hand) {
boolean isFlush = true;
String suit = hand[0].getSuit();
for(int i = 1; i < hand.length; i++) {
if(!(hand[i].getSuit().equals(suit))) {
isFlush = false;
}
}
if(isFlush){
flushn = 5;
}
}//end of flush evaluation
public static boolean hasStraight(Card[] hand) {
String[] faces = {"Ace", "Deuce", "Three", "Four", "Five", "Six",
"Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"};
int minFace = 13;
for(int i = 0; i < hand.length; i++) {
int face = 13;
for(int j = 0; j < faces.length; j++) {
if(hand[i].getFace().equals(faces[j])) {
face = j;
}
}
if(face < minFace) {
minFace = face;
}
}
if(minFace > 7) {
return false;
}
boolean isStraight = true;
for(int i = minFace+1; i < minFace+hand.length; i++) {
boolean found = false;
for(int j = 0; j < hand.length; j++) {
if(hand[j].getFace().equals(faces[i])) {
found = true;
str++;
}
}
if(!found) {
str=0;
isStraight = false;
}
}
return isStraight;
}
public static int Pair(){
int pair = 0, done = 0, handcount = 1;
int pairCheck=0;
while (done <1){
for(int i = 0; i < 4; i++){
String tempCard = DeckOfCardsTest.hand[i].getFace();
for(int j=handcount; j < DeckOfCardsTest.hand.length; j++){
if(tempCard.equals(DeckOfCardsTest.hand[j].getFace()))
pair++;
}
handcount++;
}
pairCheck = pair;
done++;
}
return pairCheck;
}//endof Pair method
public static String Results(){
String results=("High Card");
int checkHand = 0;
if (Pair()>0 ){
switch (Pair()){
case 1:
results = ("Pair");
break;
case 2:
results = ("Two Pair!");
break;
case 3:
results = ("Three of a kind!");
break;
case 4:
results = ("Full House!");
break;
case 6:
results = ("FOUR of a kind!");
break;
default:
results = ("Somthing went terribly wrong, sorry");
break;
}
}//end of pairing results
if (flushn > 0){
results = ("Flush!");
}
if (str > 0){
results = ("Straight!");
}
return results;
}
}//end of Class
There is no error, but the method never returns true
This is not true. Your current hasStraight method is almost correct and does in fact return true/false correctly. The main issue you have is that your main loop uses the static variable str. There is a bug which does not reset str to zero correctly.
In short, there are two ways to address your problem:
1) Fix the issue with str
if (!found) {
str = 0;
isStraight = false;
break;
}
2) The main loop should use the boolean result of hasStraight instead of str.
boolean b = false;
while (!b) {
DeckOfCards myDeckOfCards = new DeckOfCards();
myDeckOfCards.shuffle(); // place Cards in random order
// print the hand dealt
for (int i = 0; i < 5; i++) {
// deal and display a Card
// System.out.printf("%-19s%n", myDeckOfCards.dealCard());
hand[i] = myDeckOfCards.dealCard();
if (i % 5 == 0) { // output a newline after every fifth card,
// incase dealing 2 hands in the future
System.out.println();
}
} // end of for loop
for (int i = 0; i < hand.length; i++) {
System.out.println("" + hand[i]);
}
DeckOfCards.Pair();// check hand for pair, 2 pair, 3 of a kind, four
// of a kind, or a full house
DeckOfCards.hasFlush(hand);// check hand for flush
System.out.println("\n\n\t" + DeckOfCards.Results() + "\n\n " + DeckOfCards.str);
b = DeckOfCards.hasStraight(hand);
System.out.println("Straight= " + b);
DeckOfCards.flushn = 0;
}
If I use either of these fixes, the main loop will loop until there is a straight.
Notes:
1. I believe the minFace check should be:
if (minFace > 8) {
return false;
}
Can an ace be high?
Ace code?
boolean hasAce = false;
for (int i = 0; i < hand.length; i++) {
if (hand[i].getFace().equals("Ace"))
hasAce = true;
}
// ... Current code ....
if (!isStraight && hasAce) {
isStraight = true;
for (int i = 9; i < 13; i++) {
boolean found = false;
for (int j = 0; j < hand.length; j++) {
if (hand[j].getFace().equals(faces[i])) {
found = true;
str++;
}
}
if (!found) {
str = 0;
isStraight = false;
break;
}
}
}
return isStraight;

Poker game hand evaluator arrays condition structure

I made up a quick poker game. It generates 5 random numbers and converts those numbers into actual cards values and symbols based on their value. However, I have problems when it comes to making the hand evaluation.
So far I only did the flush right as it's really easy but even then it's not perfect (it prints that the user has a flush 5 times... ) and I would really appreciate if someone could help me with the pair, two pair, three of a kind and straight. I could do the rest afterwards but I just need a heads-up on how to do those.
Thank you in advance for your help, here is the code :
package tests;
import java.util.*;
public class TESTS {
public static void main(String[] args) {
boolean[] pack = new boolean[52]; // Array to not generate the same number twice
int[] cards = new int[5]; //The 5 unique random numbers are stored in here.
String[] cardsvalues = new String[5]; // This will assign the card's value based on the random number's value
char[] cardssymbols = new char[5];//This will assign the card's symbol based on the random number's value
char symbols[] = {'♥', '♦', '♣', '♠'}; // possible symbols that the random number can take
String values[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"}; // possible values that the random number can take
Random give = new Random();
for (int i = 0; i < cards.length; i++) { // Gives 5 unique random numbers
do {
cards[i] = give.nextInt(52);
} while (pack[cards[i]]);
pack[cards[i]] = true;
System.out.println(cards[i]);
}
for (int i = 0; i < cards.length; i++) { // This converts the number to a card symbol based on the number's value
final int numOfSymbol = cards[i] / 13;
cardssymbols[i] = symbols[numOfSymbol];
}
for (int i = 0; i < cards.length; i++) { // This converts the number to an actual card value based on the number's value.
final int numOfValues = cards[i] % 13;
cardsvalues[i] = values[numOfValues];
}
for (int i = 0; i < cardssymbols.length; i++) { // Prints the actual cards once they are converted
System.out.print(cardssymbols[i]);
System.out.println(cardsvalues[i]);
}
for (int i = 0; i < cardsvalues.length; i++) { //Here is the problem, i have no idea on how to make the handevaluator ...
if (cardsvalues[i] == cardsvalues[i] + 1) {
System.out.println("PAIR !!!");
} else if (cardsvalues[i] == cardsvalues[i] + 1 && cardsvalues[i] == cardsvalues[i] + 2) {
System.out.println("TRIPS !!!");
} else if (cardssymbols[0] == cardssymbols[1] && cardssymbols[1] == cardssymbols[2] && cardssymbols[2] == cardssymbols[3] && cardssymbols[3] == cardssymbols[4]) {
System.out.println("FLUSHHH");
}
}
}
Hints:
To simplify testing for straights and sorting by highest card, it is easier to represent ranks by their indexes, and only translate them to the symbols for printing.
Using a Card object allows for clearer code.
The Java Collection framework has useful functions for shuffling, slicing and sorting.
My solution:
public class Test {
static final char[] suits = {'♥', '♦', '♣', '♠'};
static final String[] ranks = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};
static class Card {
final int suit;
final int rank;
Card(int s, int r) {
suit = s;
rank = r;
}
#Override
public String toString() {
return suits[suit] + ranks[rank]; // or however you want the cards to be printed
}
}
public static void main(String[] args) {
List<Card> deck = new ArrayList<>();
for (int s = 0; s < suits.length; s++) {
for (int r = 0; r < ranks.length; r++) {
deck.add(new Card(s,r));
}
}
Collections.shuffle(deck);
List<Card> hand = deck.subList(0,5);
Collections.sort(hand, Comparator.comparing(c -> c.rank));
System.out.println("Your hand is: " + hand);
System.out.println(value(hand));
}
static String value(List<Card> hand) {
boolean straight = true;
boolean flush = true;
for (int i = 1; i < hand.size(); i++) {
straight &= hand.get(i - 1).rank + 1 == hand.get(i).rank;
flush &= hand.get(i - 1).suit == hand.get(i).suit;
}
if (straight && flush) {
return "Straight Flush from " + hand.get(4);
}
List<Run> runs = findRuns(hand);
runs.sort(Comparator.comparing(r -> -r.rank));
runs.sort(Comparator.comparing(r -> -r.length));
if (runs.get(0).length == 4) {
return "Four of a Kind: " + runs;
}
if (runs.get(0).length == 3 && runs.get(1).length == 2) {
return "Full House: " + runs;
}
if (straight) {
return "Straight from " + hand.get(4);
}
if (runs.get(0).length == 3) {
return "Three of a Kind: " + runs;
}
if (runs.get(1).length == 2) {
return "Two pair: " + runs;
}
if (runs.get(0).length == 2) {
return "Pair: " + runs;
}
return "High card: " + runs;
}
/** Represents {#code length} cards of rank {#code rank} */
static class Run {
int length;
int rank;
#Override
public String toString() {
return ranks[rank];
}
}
static List<Run> findRuns(List<Card> hand) {
List<Run> runs = new ArrayList<>();
Run run = null;
for (Card c : hand) {
if (run != null && run.rank == c.rank) {
run.length++;
} else {
run = new Run();
runs.add(run);
run.rank = c.rank;
run.length = 1;
}
}
return runs;
}
}
Example output:
Your hand is: [♣10, ♥J, ♦J, ♠K, ♥K]
Two pair: [K, J, 10]

Arraylist of objects to Array of strings

I'm trying to convert an ArrayList that contains "cards", or objects that store two numbers, a rank and a suit. Normally to get a single instance of the card, I use:
dealer.dealerhand.get(1).showstats();
Where showstats returns a string and is:
public String showstats()
{
String realsuit = "";
if(this.suit == 0)
{
realsuit = "Diamonds";
}
else if(this.suit == 1)
{
realsuit ="Hearts";
}
else if(this.suit == 2)
{
realsuit = "Clubs";
}
else if(this.suit == 3)
{
realsuit = "Spades";
}
String str = "My rank is: " + this.rank + " My Suit is: " + realsuit;
return str;
}
What I've tried so far is:
public String[] getStats()
{
String[] dealerstats = this.dealerhand.toArray(new String[this.dealerhand.size()]);
return dealerstats;
}
and
public String[] getStats()
{
String[] dealerstats = {""};
for(int i = 0; i < this.dealerhand.size(); i++)
{
dealerstats[i] = (dealerhand.get(i).showstats());
}
return dealerstats;
}
But they both don't work. The end goal would be a string array of the cards in the dealerhand ArrayList, that I will print out using JList. Thanks!
For this:
public String[] getStats() {
for(int i = 0; i < this.dealerhand.size(); i++) {
dealerstats[i] = (dealerhand.get(i).showstats());
}
return dealerstats;
}
make sure to initialize your String array, such as below:
public String[] getStats(Dealer dealer) { // Input a dealer
String[] dealerstats = new String[dealer.dealerhand.size()]; // Initialize String array
for(int i = 0; i < this.dealerhand.size(); i++) {
dealerstats[i] = dealerhand.get(i).showstats();
}
return dealerstats;
}
I am also assuming you have a Dealer object, as you seem to reference one in your question.
Your second attempt is almost correct. You created the array but without giving it the correct size. The String[] dealerstats size should be the size of the ArrayList dealerhand:
public String[] getStats()
{
String[] dealerstats = new String[ dealerhand.size() ];
for( int i = 0; i < dealerstats.length; ++i )
dealerstats[i] = dealerhand.get(i).showstats();
return dealerstats;
}
If you define a toString() method in your Card class you can print the ArrayList out without any conversion (Live Ideone Example here):
public class Card{
...
#Override public String toString(){
return "My rank is: " + this.rank + " My Suit is: " + this.suit;
}
}
Then you can just use:
List<Card> dealerCards = new ArrayList<Card>();
dealerCards.add(new Card(5, "Hearts"));
dealerCards.add(new Card(10, "Diamonds"));
System.out.println(dealerCards);
Output: ["My rank is: 5 My Suit is: Hearts", "My rank is: 10 My Suit is: Diamonds"]

how to print all of arrays with for loop in java

I have array in String. I want to use for loop to print all of the objects. I was under the impression this would be done by making for loop then returning the String. I am not sure what I need to change to accomplish this.
Following is my effort:
public class SolarSystem {
private Planet[] planets;
private int position = 0;
public SolarSystem(int size) {
planets = new Planet[size];
}
public void add(Planet planet) {
planets[position] = planet;
position++;
}
public String toString(){
for(int i = 0; i < planets.length; i++){
}
return toString();
}
}
ADDED PLANET CLASS
public class Planet {
String name;
int moons;
public Planet(String name, int moons)
{
this.moons = moons;
this.name = name;
}
public String toString() {
return "The Planet " + name + " Has " + moons + " Moon(s) \r\n ";
}
}
You can try using a StringBuilder:
public String toString() {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < planets.length; i++){
sb.append(planets[i].getName()); // getName() or toString()
sb.append("\n");
}
return sb.toString();
}
Override toString() method in Planet class, and use below code :
public String toString(){
String result = "";
for(int i = 0; i < planets.length; i++){
result += planets[i].toString(); // append comma if you need to separate it,
// and most of all handle nulls
}
return result;
}
public String toString() {
StringBuilder mainresult = new StringBuilder();
for(int i = 0; i < planets.length; i++){
StringBuilder result = new StringBuilder();
String newLine = System.getProperty("line.separator");
result.append( planets[i].getClass().getName() );
result.append( " Object {" );
result.append(newLine);
//determine fields declared in this class only (no fields of superclass)
Field[] fields = this.getClass().getDeclaredFields();
//print field names paired with their values
for ( Field field : fields ) {
result.append(" ");
try {
result.append( field.getName() );
result.append(": ");
//requires access to private field:
result.append( field.get(this) );
} catch ( IllegalAccessException ex ) {
System.out.println(ex);
}
result.append(newLine);
}
result.append("}");
//if it is the first one then no new line added
if(i==0)
{
mainresult.append(result.toString());
continue;
}
mainresult.append(newLine);
mainresult.append(result.toString());
}
return mainresult.toString();
}
Override toString() Method
#Override
public String toString() {
return "SolarSystem [te=" + Arrays.toString(te) + ", position=" + position + "]";
}
If you have this overidden method in your planet class
public String toString(){
StringBuilder result = new StringBuilder();
String NEW_LINE = System.getProperty("line.separator");
result.append(" planetProperty1: ").append (planetProperty1).append(NEW_LINE);
result.append(" planetProperty2: ").append (planetProperty2).append(NEW_LINE);
return result.toString();
}
then from the calling class you can iterate over the collection calling
System.out.println (planets[i].toString());

Java: Printing / returning array from a class

I created a class for a bingo game. I get an error saying "'class' expected". How could I return the values in the array to the main starter?
Any other comments would also be helpful.
Thank you.
import java.util.Random;
public class Card
{
Random generator = new Random();
private final int BOARDMAX = 4;
private final int NUMMAX = 59;
int i, j, m, n;
private int [][] ArrayBoard = new int[BOARDMAX][BOARDMAX];
String [][] StrArrayBoard = new String [BOARDMAX][BOARDMAX];
public void RandomNumGenerator()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
ArrayBoard[i][j] = generator.nextInt (NUMMAX+1);
}
}
}
public String ShowBoard()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
m=i;
n=j;
if (j != BOARDMAX)
StrArrayBoard[m][n] = ArrayBoard[m][n] + " ";
else
StrArrayBoard[m][n] = ArrayBoard[m][n] + " \n";
}
}
return StrArrayBoard[i][j];
}
public void ShowMark()
{
for (i = 0; i<BOARDMAX; i++)
{
for (j = 0; j<BOARDMAX; j++)
{
if (CardCheck [i][j] == 1)
StrArrayBoard[i][j] = ArrayBoard[i][j] + "* ";
else
StrArrayBoard[i][j] = ArrayBoard[i][j] + " ";
if (j == BOARDMAX)
ArrayBoard[i][j] = ArrayBoard[i][j] + "\n";
}
}
}
public String toString()
{
return ArrayBoard[][];
}
}
With toString() you need to return a String object but actually you try to return an int[][]. The same is true for ShowBoard, you try to return an array of Stringarrays which is not a compatible type.
Here's the fix:
public String ShowBoard() {
// your code to populate StrArrayBoard
StringBuilder boardBuilder = new StringBuilder();
for (String[] row:StrArrayBoard)
for (String cell:row)
sb.append(cell);
return boardBuilder.toString();
}
public String toString() {
return ShowBoard();
}
I suggest to refactor the code and rename methods and fields:
ShowBoard() --> getBoardAsString()
ArrayBoard --> arrayBoard
StrArrayBoard --> strArrayBoard
And there's no need to declare StrArrayBoard as a field (class member) just because you only need it inside the ShowBoard method. Declare it there as a local variable.
Adding to the bugs others have pointed:
You have if (CardCheck [i][j] == 1), but the array CardCheck is not declared anywhere.
You have ArrayBoard[i][j] = ArrayBoard[i][j] + "\n"; but ArrayBoard is an int array, you cannot add a string "\n" to it's member.
The compiler will complain because of the error on your code:
public String toString()
{
return ArrayBoard[][];
}
It can't convert int[][] (which is your ArrayBoard) to String. My suggestion is that you populate all values stored in StrArrayBoard in a StringBuffer and return the StringBuffer.toString() in the toString() method.
The toString() method requires a String.
Hope this helps.
public String toString()
{
return ArrayBoard[][];
}
This method expects to return a String but you are returning a 2D Integer array, what you need is a String. the toString() method returns a string representation of the object, so in this case, what you can do is to use a StringBuilder to build the string representation of the array and then, use the .toString() of the StringBuilder to return the string representing the 2D Array.
Also, as noted by Alois Cochard, you variable naming does not follow convention. Variable names in Java use a camel case notation.
I for one don't really understand your question but I've got a couple of comments.
The class variables i and j should be local variables in each method.
Your naming convention is nonstandard, seems like a more C# convention. Start variable and method names with a lower case.
CardCheck isn't defined anywhere. I presume it is meant to indicate if a number on a square has been checked, in which case it should be a boolean and not an int.
toString doesnt return a string. You can use Arrays.toString to help you.
Similarily, ShowBoard just returns one element of an array, you probably wanted to show the entire board there.
For your toString and ShowBoard methods you probably want to use a StringBuilder to build up the string representation.
StringBuilder builder = new StringBuilder();
for (int i=0; i<BOARDMAX; i++) {
for (int j=0; j<BOARDMAX; j++) {
builder.append(StrArrayBoard[i][j]);
}
builder.append('\n');
}
return builder.toString();
Here's a version of your class that compiles (and I changed some field names and modifiers to adhere to standard conventions). Try this:
public class Card{
private final Random generator = new Random();
private static final int BOARDMAX = 4;
private static final int NUMMAX = 59;
int i, j, m, n;
private final int[][] arrayBoard = new int[BOARDMAX][BOARDMAX];
private final String[][] strArrayBoard = new String[BOARDMAX][BOARDMAX];
// do something here please
private int[][] CardCheck;
public void RandomNumGenerator(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
arrayBoard[i][j] = generator.nextInt(NUMMAX + 1);
}
}
}
public String ShowBoard(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
m = i;
n = j;
if(j != BOARDMAX){
strArrayBoard[m][n] = arrayBoard[m][n] + " ";
} else{
strArrayBoard[m][n] = arrayBoard[m][n] + " \n";
}
}
}
return strArrayBoard[i][j];
}
public void ShowMark(){
for(i = 0; i < BOARDMAX; i++){
for(j = 0; j < BOARDMAX; j++){
if(CardCheck[i][j] == 1){
strArrayBoard[i][j] = arrayBoard[i][j] + "* ";
} else{
strArrayBoard[i][j] = arrayBoard[i][j] + " ";
}
if(j == BOARDMAX){
// this is probably what you mean:
strArrayBoard[i][j] = arrayBoard[i][j] + "\n";
}
}
}
}
#Override
public String toString(){
// this is probably what you mean:
return Arrays.deepToString(strArrayBoard);
}
}

Categories