有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用开关检查字符串是否为数字

我必须制作一个程序,通过使用^{,告诉我在键盘上键入的String是否是一个数字。我知道如何使用try-and-catch,但我不知道如何使用switch

有什么建议吗


共 (4) 个答案

  1. # 1 楼答案

    在Java7之前,您可以使用switch(String)语句


    但是在这里,你已经有足够的switch(int)和一些解决方法:

    public static void main(String[] args) throws Exception {
        String a = "2";
    
        switch (Integer.parseInt(a)) {
        default: 
            System.out.print("is a number");
            break;
        }
    }   
    
  2. # 2 楼答案

    我提出了一个较短的代码,但它使用正则表达式,如果Halo只是从Java开始,他可能还没有看到这个主题。但它也回答了这个问题,所以这里是:

    Scanner scanner = new Scanner(System.in);
    String expression = scanner.nextLine();
    String matches = new Boolean(expression.matches("\\d+")).toString();
    switch (matches) {
    case "true":
        System.out.println("IT'S a number");
        break;
    case "false":
        System.out.println("NOT a number");
    }
    scanner.close();
    
  3. # 3 楼答案

    这就是我向一些同学询问并静静思考的解决方案

    public static void main(String[] args) {
        // TODO Auto-generated method stub 
    
    
        Scanner entry = new Scanner(System.in);
        String myNumber;
        int tf;
        myNumber = entry.next();
    
        try {
            Double.parseDouble(myNumber);
            tf = 1;
        }
    
        catch (Exception e) {
            tf = 0;
        }
    
    
        switch(tf) {
    
        case 1:
            System.out.println("Is a number");
        break;
    
        default:
            System.out.println("No es un número");
            break;
    
        }
    
    
    
    
    }
    

    感谢社区如此友善

  4. # 4 楼答案

    您需要检查^{中的每个字符。像这样的东西可能会管用

    static boolean isNumber(String s) {
        if (s == null) {
            // Debatable.
            return false;
        }
        int decimalCount = 0;
        for (int i = 0; i < s.length(); i++) {
            switch (s.charAt(i)) {
                case '0':
                case '1':
                case '2':
                case '3':
                case '4':
                case '5':
                case '6':
                case '7':
                case '8':
                case '9':
                    // These are all allowed.
                    break;
                case '.':
                    if (i == 0 || decimalCount > 0) {
                        // Only allow one decimal in the number and not at the start.
                        return false;
                    }
                    decimalCount += 1;
                    break;
                default:
                    // Everything else not allowed.
                    return false;
            }
        }
        return true;
    }