我正在学习Java编程入门课程,我想知道是否有捷径可以让我在if
语句中做什么。
我的问题是:当我为编号卡2-10写if
语句时,我是需要为每个数字单独写一个语句,还是可以将它们合并成一个if
语句?
检查我的代码在哪里说是一个整数(显然不是Java符号)。下面是我的代码片段来澄清:
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.");
}
}
}
你可以这样做:
char c = string.charAt(0);
if (Character.isDigit(c)) {
// do something
}
x.substring(0,1)
与string.charAt(0)
基本相同。区别在于charAt返回char
,而substring返回String
。
如果这不是家庭作业,我建议你用StringUtils.isNumeric
代替。你可以说:
if (StringUtils.isNumeric(x.substring(0, 1))) {
System.out.println("is numeric");
}
另一种将字符串转换为整型的方法是:
Integer number = Integer.valueOf("10");
另一种可以考虑的方法是使用类或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
}
}
这是我能想到的最简洁的解决方案:
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));
}