Inputting a string into my code that an int is required and I get a java error how can I fix this?

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

Inputting a string into my code that an int is required and I get a java error how can I fix this?

问题

当我错误地将一个字符串输入到下面的代码中进行测试时,控制台会显示一个红色的Java错误消息。然而,在我的if语句中,我添加了一个else部分,如果用户没有输入if语句的条件,即输入0-100之间的数字,程序应该终止。为什么会出现这种情况,我该如何解决?

            Scanner input = new Scanner(System.in);
            System.out.println("请输入一个数字:");
            int decimal = input.nextInt();
            if (decimal > 0 && decimal <= 100) {
                //代码
            }
            else {
                System.exit(0);
            }
英文:

When I input a string into the code below by mistake as a test, I get a red java error message in my console. However, within my if statement I added an else part which should end the program if the user doesn't input the if statement condition i.e a number between 0-100. Why this is and how can I fix it?

        Scanner input = new Scanner(System.in);
        System.out.println(&quot;Enter a number: &quot;);
        int decimal = input.nextInt();
        if (decimal &gt; 0 &amp;&amp; decimal &lt;= 100) {
            //code 
        }
        else {
            System.exit(0);
        }

答案1

得分: 1

nextInt方法在输入不是整数时会抛出异常。如果您想要防止这种情况,只需在读取之前使用方法hasNextInt进行检查。

英文:

The nextInt method throws an exception if the input is not an integer. If you want to prevent this, just use the method hasNextInt to check before read it.

huangapple
  • 本文由 发表于 2020年7月26日 06:14:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/63094089.html
匿名

发表评论

匿名网友

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

确定