尝试-捕获在我的扫描器循环中出现问题 – Java

huangapple go评论81阅读模式
英文:

Try-Catch gets in a loop for my Scanner - Java

问题

在我的Java程序中,我正在询问玩家的年龄,如果用户在问题提出时输入了一个字符串,我需要显示错误信息checkError(4),然后再次询问正确的玩家年龄,直到用户输入一个数字为止。

问题在于,当年龄是字符串时,代码陷入循环,然后始终打印字符串“玩家年龄是多少?”我在一些网站上看到,如果在while语句中使用in.hasNextInt(),可以解决这个问题,但在这种情况下,我只有在"check"为true时才运行while循环。

如何解决这个问题?谢谢

check = true;
while (check){
    try { 
        System.out.println("玩家年龄是多少?");
        if(in.hasNextInt()){
            edad = in.nextInt();
            if (edad > 6 && edad < 100){
                check = false;
            } else {
                System.out.println(checkError(3));
            }
        } else { }
    } catch(Exception e) { // 年龄是字符串
        System.out.println(checkError(4));
    }
}
英文:

In my java program, I am asking which is the age of the player, if the user writes a string when it was made the question I need to show the error checkError(4) and ask again which is the correct age of the player until the user writes a number.

The problem here is that the code gets in a loop when the age is a string and then always prints the string "Age of the player?". I saw in some websites that it can be solved the problem if in the while statement I use in.hasNextInt() but in this case, I am running the while if "check" is true

How can I solve this issue? Thanks

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

答案1

得分: 1

尝试像这样进行:

public static void main(String[] args) {
    int edad;
    boolean check = true;
    Scanner in = new Scanner(System.in);
    while (check) {
        try {
            System.out.println("玩家的年龄是多少?");
            if (in.hasNext()) {
                String s = in.next(); // 以字符串形式读取
                edad = Integer.parseInt(s, 10); // 转换为整数,如果是NaN则抛出异常
                if (edad > 6 && edad < 100) {
                    check = false;
                }
            } else {
            }
        } catch (NumberFormatException e) { // edad 是一个字符串
            System.out.println(e.toString());
        }
    }
}
英文:

try it like this :

public static void main(String[] args) {
    int edad;
    boolean check = true;
    Scanner in = new Scanner(System.in);
    while (check) {
        try {
            System.out.println(&quot;Age of the player?&quot;);
            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 &gt; 6 &amp;&amp; edad &lt; 100) {
                    check = false;
                }
            } else {
            }
        } catch (NumberFormatException e) { // Edad is a string
            System.out.println(e.toString());
        }
    }
}

答案2

得分: 0

只是更容易我认为根本不要使用**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("玩家的年龄(从6到100岁)?");
        String s = in.nextLine(); // 获取用户输入
        // 用户提供了整数数值吗?
        if (!s.matches("\\d+")) {
            // 没有...
            System.err.println("无效输入!(" + s + ")。请重试...");
        }
        // 有...
        else {
            edad = Integer.parseInt(s, 10);  // 转换为整数
            if (edad > 6 && edad < 100) {    // 检查范围
                check = false;   // 在范围内。 :)
            }
            // 超出范围...
            else {
                System.err.println("年龄(" + edad + ")超出范围!请重试...");
            }
        }
    }
    System.out.println("玩家年龄为: --> " + edad);  
}
英文:

It's just easier (I think) to not even play with the 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(&quot;Age of the player (6 to 100 inclusive)?&quot;);
        String s = in.nextLine(); // Get User input
        // Did the User provide an integer numerical value?
        if (!s.matches(&quot;\\d+&quot;)) {
            // Nope...
            System.err.println(&quot;Invalid Entry! (&quot; + s + &quot;). Try Again...&quot;);
        }
        // Yup...
        else {
            edad = Integer.parseInt(s, 10);  // Convert it to integer
            if (edad &gt; 6 &amp;&amp; edad &lt; 100) {    // Check Range
                check = false;   // is in range. :)
            }
            // Is out of range...
            else {
                System.err.println(&quot;Age (&quot; + edad + &quot;) is out of range! Try Again...&quot;);
            }
        }
    }
    System.out.println(&quot;Player&#39;s Age Is: --&gt; &quot; + edad);  
}

huangapple
  • 本文由 发表于 2020年10月18日 08:13:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/64408546.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定