我正在继续学习我的Intro编程课程,并想知道我在if语句中所做的工作是否有捷径。
基本上,我的程序收到一张扑克牌的两个字符的缩写,并返回全卡名(."QS“返回”黑桃皇后“()
现在我的问题是:当我为编号为2-10的卡片编写if语句时,是否需要为每个数字单独设置一个语句,还是可以将它们合并到一个if语句中?
检查我的代码在哪里显示是整数(显然不是符号)。下面是我的代码片段以澄清:
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.");
}
}
}发布于 2013-01-20 03:42:35
你可以这样做:
char c = string.charAt(0);
if (Character.isDigit(c)) {
// do something
}x.substring(0,1)和string.charAt(0)几乎一样。区别是charAt返回一个char,子字符串返回一个String。
如果这不是作业,我建议你用StringUtils.isNumeric代替。你可以说:
if (StringUtils.isNumeric(x.substring(0, 1))) {
System.out.println("is numeric");
}发布于 2013-01-20 03:46:13
另一种将字符串转换为int的方法是:
Integer number = Integer.valueOf("10");另外,您可能考虑的另一种方法是使用类或枚举。
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
}
}发布于 2013-01-20 03:45:45
这是我能想到的最简单的解决方案:
private static Map<String, String> names = new HashMap<String, String>() {{
put("A", "Ace");
put("K", "King");
put("Q", "Queen");
put("J", "Jack");
}};然后在你的主旋律里:
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));
}https://stackoverflow.com/questions/14421461
复制相似问题