问题
import java.util.ArrayList;
public class Card {
int number;
String suit;
public Card(int number, String suit) {
this.number = number;
this.suit = suit;
@Override
public String toString() {
String[] high = {
"Jack",
"Queen",
"King"
};
String type;
if (number < 10) {
return String.valueOf(this.number) + " of " + this.suit;
}
else {
return high[this.number-10] + " of " + this.suit;
}
//return suit + " of " + type;
//return String.valueOf(number) + " of " + suit;
}
}
public static void main(String[] args) {
String[] suit = {
"Clubs",
"Diamonds",
"Spades",
"Hearts"
};
// String[] high = {
// "Jack",
// "Queen",
// "King"
// };
ArrayList<Card> deckOfCards = new ArrayList<Card>(52);
for (int j = 0; j < 4; j++) {
for (int i = 0; i < 13; i++) {
deckOfCards.add(new Card (i+1, suit[j]));
currentCard.toString();
}
}
// @Override
// public String toString(Card card) {
//
// this.suit = suit;
// this.number = number;
//
// String type;
//
// if (number < 10) {
// type = Integer.toString(number);
// }
// else {
// type = high[i-number];
// }
//
// return suit + " of " + type;
// }
// currentCard.toString();
}
}
Everything works except the toString method within the Card class. Not 100% sure what the problem is, error message is
Card.java:13: error: ';' expected public String toString() {
Any help is appreciated Thank You
回答1:
Your toString()
method is inside your Card(int number, String suite)
constructor. Move it out.
回答2:
the String method
is inside of the constructor of the class Cards, move it outside so you can use it, and so you can have a valid Card constr
.
回答3:
Place the toString outside of your constructor.
public Card(int number, String suit) {
this.number = number;
this.suit = suit;
}
@Override
public String toString() {
String[] high = {
"Jack",
"Queen",
"King"
};
String type;
if (number < 10) {
return String.valueOf(this.number) + " of " + this.suit;
}
else {
return high[this.number-10] + " of " + this.suit;
}
}
回答4:
Your toString() method is inside your constructor;
here is the corrected code
public class Card {
int number;
String suit;
public Card(int number, String suit) {
this.number = number;
this.suit = suit;
}
@Override
public String toString() {
String[] high = {
"Jack",
"Queen",
"King"
};
String type;
if (number < 10) {
return String.valueOf(this.number) + " of " + this.suit;
}
else {
return high[this.number-10] + " of " + this.suit;
}
//return suit + " of " + type;
//return String.valueOf(number) + " of " + suit;
}
// your main starts from here..
dont forget to format if youre in eclipse ctrl+shift+f
来源:https://stackoverflow.com/questions/35306117/how-to-make-tostring-method-within-object