在"if"语句中将String转换为int

0 java string int integer if-statement

我正在我的Intro Java编程课程中工作,并且想知道我在一个if声明中是否有一个快捷方式.

基本上,我的程序收到一张扑克牌的双字符缩写并返回完整的卡片名称(即"QS"返回"黑桃皇后".)

现在我的问题是:当我if为编号的卡2-10 编写语句时,我是否需要为每个数字单独声明,还是可以将它们组合在一个if语句中?

检查我的代码所在的位置IS AN INTEGER(显然不是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.");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*lan 5

你可以这样做:

    char c = string.charAt(0);
    if (Character.isDigit(c)) {
        // do something
    }
Run Code Online (Sandbox Code Playgroud)

x.substring(0,1)几乎是一样的string.charAt(0).区别在于charAt返回a char和substring返回a String.

如果这不是作业,我建议你StringUtils.isNumeric改用.你可以说:

    if (StringUtils.isNumeric(x.substring(0, 1))) {
        System.out.println("is numeric");
    }
Run Code Online (Sandbox Code Playgroud)