繁体   English   中英

Try-Catch 进入我的扫描仪的循环 - Java

[英]Try-Catch gets in a loop for my Scanner - Java

在我的 java 程序中,我问的是玩家的年龄,如果用户在提出问题时写了一个字符串,我需要显示错误 checkError(4) 并再次询问玩家的正确年龄,直到用户写一个数字。

这里的问题是当年龄是一个字符串时代码进入循环,然后总是打印字符串“玩家年龄?”。 我在一些网站上看到如果在 while 语句中使用 in.hasNextInt() 可以解决问题,但在这种情况下,如果“check”为真,我正在运行 while

我该如何解决这个问题? 谢谢

 check = true;
  while (check){
    try { 
        System.out.println("Age of the player?");
        if(in.hasNextInt()){
            edad = in.nextInt();
            if (edad > 6 && edad < 100){
                check = false;
            } else {
                System.out.println(checkError(3));
            }
        } else { }
    } catch(Exception e) { // Edad is a string
        System.out.println(checkError(4));
    }
  }

像这样尝试:

public static void main(String[] args) {
    int edad;
    boolean check = true;
    Scanner in = new Scanner(System.in);
    while (check) {
        try {
            System.out.println("Age of the player?");
            if (in.hasNext()) {
                String s = in.next(); //read as string
                edad = Integer.parseInt(s, 10); // Convet to int and throw exception if NaN
                if (edad > 6 && edad < 100) {
                    check = false;
                }
            } else {
            }
        } catch (NumberFormatException e) { // Edad is a string
            System.out.println(e.toString());
        }
    }
}

甚至不玩Try/Catch更容易(我认为):

public static void main(String[] args) {
    int edad = 0;
    boolean check = true;
    Scanner in = new Scanner(System.in);
    while (check) {
        System.out.println("Age of the player (6 to 100 inclusive)?");
        String s = in.nextLine(); // Get User input
        // Did the User provide an integer numerical value?
        if (!s.matches("\\d+")) {
            // Nope...
            System.err.println("Invalid Entry! (" + s + "). Try Again...");
        }
        // Yup...
        else {
            edad = Integer.parseInt(s, 10);  // Convert it to integer
            if (edad > 6 && edad < 100) {    // Check Range
                check = false;   // is in range. :)
            }
            // Is out of range...
            else {
                System.err.println("Age (" + edad + ") is out of range! Try Again...");
            }
        }
    }
    System.out.println("Player's Age Is: --> " + edad);  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM