2013-01-20 53 views
0

我在我的Intro Java编程课程中处于领先地位,并且想知道在if语句中是否有快捷方式。将字符串转换为“if”语句中的int

基本上,我的程序收到扑克牌两个字符缩写,并返回全卡的名称

现在我的问题是(即“QS”返回“黑桃皇后”): 当我为编号卡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."); 
     } 
    } 
} 
+1

您是否将“ten of spades”输入为“10S”或“TS”? – Bohemian

+0

应该是10S,它会在任何尝试转换为字符时抛出一个曲线球 – Shwheelz

+0

因此,任何套装中的10个是_three_字符的缩写? –

回答

5

你可以这样做,而不是:

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"); 
    } 
+1

谢谢,我认为第一个就足够了。我认为如果我为此单独使用一个IF语句,我将能够解决这10个问题。竖起大拇指为快速回应^ - ^ – Shwheelz

0

这是我能想到的最简短的解决方案:那么在

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)); 
} 
1

另一种方式将字符串转换到一个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 
    } 
}