Reputation: 1
I'm working ahead in my Intro Java programming course and was wondering if there is a shortcut to what I am trying to do in an if
statement.
Basically, my program receives a two-character abbreviation for a playing card and returns the full card name (i.e. "QS" returns "Queen of Spades.")
Now my question is:
When I write the if
statements for the numbered cards 2-10, do I need a separate statement for each number or can I combine them in one if
statement?
Check where my code says IS AN INTEGER (obviously not Java notation.) Here is a fragment of my code to clarify:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.print("Enter the card notation: ");
String x = in.nextLine();
if (x.substring(0,1).equals("A")){
System.out.print("Ace");
}
else if(x.substring(0,1) IS AN INTEGER) <= 10)){ // question is about this line
System.out.print(x);
}
else{
System.out.println("Error.");
}
}
}
Upvotes: 0
Views: 6102
Reputation: 67360
You can do this instead:
char c = string.charAt(0);
if (Character.isDigit(c)) {
// do something
}
x.substring(0,1)
is pretty much the same as string.charAt(0)
. The difference is charAt returns a char
and substring returns a String
.
If this weren't homework, I'd recommend you use StringUtils.isNumeric
instead. You'd be able to say:
if (StringUtils.isNumeric(x.substring(0, 1))) {
System.out.println("is numeric");
}
Upvotes: 5
Reputation: 425033
This is the briefest solution I can think of:
private static Map<String, String> names = new HashMap<String, String>() {{
put("A", "Ace");
put("K", "King");
put("Q", "Queen");
put("J", "Jack");
}};
then in your main:
String x = in.nextLine();
if (x.startsWith("10")) { // special case of two-character rank
System.out.print("Rank is 10");
} else if (Character.isDigit(x.charAt(0)){
System.out.print("Rank is " + x.charAt(0));
} else
System.out.print("Rank is: " + names.get(x.substring(0,1));
}
Upvotes: 0
Reputation: 1179
Another way to convert a string to an int is:
Integer number = Integer.valueOf("10");
Also another approach you might consider is using a class or enum.
public class Card {
// Feel free to change this
public char type; // 1 - 10, J, Q, K, A
public char kind; // Spades, Hearts, Clubs, Diamonds
public Card(String code) {
type = code.charAt(0);
kind = code.charAt(1);
}
public boolean isGreaterThan(Card otherCard) {
// You might want to add a few helper functions
}
}
Upvotes: 1