我如何在我的代码中去除这个Java异常错误?

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

How can I remove this java exception error in my code?

问题

以下是您提供的内容的翻译部分:

当我错误地将一个字符串作为测试输入到下面的代码中时,控制台会显示一个红色的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);
            }

当我输入一个字符串时,会显示以下消息。然而,我只想告诉用户他们输入了错误的值,我希望程序退出。

Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:864)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at MainHandler.main(MainHandler.java:22)

我曾尝试使用hasNextInt来消除异常错误,但是当我使用hasNextInt时会出现错误。链接:https://i.stack.imgur.com/LvQYr.jpg

英文:

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?

MY CODE

        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);
        }

When I input a string this message gets displayed. However, I just wanted to tell the user they exerted the wrong value and I wanted the program to quit.

Exception in thread &quot;main&quot; java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:864)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at MainHandler.main(MainHandler.java:22)

I did try use hasNextInt at one point to try get rid of the exception error but I get an error when I use hasNextInt. https://i.stack.imgur.com/LvQYr.jpg

答案1

得分: 0

你需要使用 double 类型,如果你输入的是小数。同时,将你的代码放在 try/catch 块内。

try {
    Scanner input = new Scanner(System.in);
    System.out.println("输入一个数字:");
    double decimal = input.nextDouble();
    if (decimal > 0 && decimal <= 100) {
    }
    else {
        System.exit(0);
    }
} catch (Exception e) {
    System.out.println(e);
}
英文:

You would need double if you are entering decimal numbers and put your code inside try/catch block

try{
            Scanner input = new Scanner(System.in);
            System.out.println(&quot;Enter a number: &quot;);
            double decimal = input.nextDouble();
            if (decimal &gt; 0 &amp;&amp; decimal &lt;= 100) {
            }
            else {
                System.exit(0);
            }
        }catch (Exception e){
            System.out.println(e);
        }

答案2

得分: 0

尝试将您的代码放在try和catch块中,如下所示:

try {
    int decimal = input.nextInt();
    if (decimal > 0 && decimal <= 100) {
        // 代码部分
    } else {
        System.exit(0);
    }
} catch (Exception e) {
    System.out.println("您输入了错误的值");
}
英文:

Try binding your code inside try and catch blocks like this:

try{
 int decimal = input.nextInt();
        if (decimal &gt; 0 &amp;&amp; decimal &lt;= 100) {
            //code 
        }
        else {
            System.exit(0);
        }

}
catch(Exception e){
  System.out.println(&quot;You enter wrong value&quot;);
}

答案3

得分: 0

尝试使用类似这样的代码。将你的输入放在 try-catch 中,只要出现 Exception,就要求用户再次输入一个数字。一旦输入有效(是一个数字),你可以继续进行你的代码:

boolean canProceed = false;
int number = -1;

while (!canProceed) {
    try {
        Scanner input = new Scanner(System.in);
        System.out.println("请输入一个数字:");
        number = Integer.parseInt(input.nextLine());
        canProceed = true;
    } catch (Exception e) {
        System.out.println("无效的输入。");
    }
}

if (number > 0 && number <= 100) {
    System.out.println("没问题");
}
else {
    System.exit(0);
}
英文:

Try with something like this. You surround your input inside a try-catch and as long as you get an Exception, you ask the user to put a number again. As soon as the input is valid (a number) you can proceed with your code:

    boolean canProceed = false;
    int number = -1;
    
    while (!canProceed) {
        try {
            Scanner input = new Scanner(System.in);
            System.out.println(&quot;Enter a number: &quot;);
            number = Integer.parseInt(input.nextLine());
            canProceed = true;
        } catch (Exception e) {
            System.out.println(&quot;Invalid input.&quot;);
        }
    }
    
    if (number &gt; 0 &amp;&amp; number &lt;= 100) {
        System.out.println(&quot;That&#39;s fine&quot;);
    }
    else {
        System.exit(0);
    }

答案4

得分: 0

你发布的代码在从一开始提供输入的情况下运行良好。然而,考虑到你的 "输入一个数字:" 消息,我想你希望用户以交互方式提供输入,在这种情况下,你将需要实现一个等待循环:

Scanner input = new Scanner(System.in);
System.out.println("输入一个数字:");
while (!input.hasNextInt()) {
    if (input.hasNextLine()) {
        input.nextLine(); // 我们得到了输入,但不是数字,将其丢弃
    }
}
int decimal = input.nextInt();
if (decimal > 0 && decimal <= 100) {
    // 代码
}
else {
    System.exit(0);
}

在这种情况下,循环将持续进行,直到找到一个整数从输入中读取,如果输入行不以整数开头,则丢弃这些输入行。

英文:

The code you posted works just fine if the input is provided from the start. However given your "Enter a number:" message I suppose you want the user to provide the input interactively, in which case you'll have to implement a waiting loop :

Scanner input = new Scanner(System.in);
System.out.println(&quot;Enter a number: &quot;);
while (!scanner.hasNextInt()) {
    if (scanner.hasNextLine()) {
        scanner.nextLine(); // we&#39;ve got something but it&#39;s not a number, discard it
    }
}
int decimal = input.nextInt();
if (decimal &gt; 0 &amp;&amp; decimal &lt;= 100) {
    //code 
}
else {
    System.exit(0);
}

In this case the loop will continue until it finds an integer to read from the input, discarding lines of input if they don't start with an integer.

答案5

得分: 0

我觉得我应该在这里加入这个,因为这是另一种灵活的选择来完成任务。它使用了 Scanner#nextLine() 方法进行输入验证,以确保所提供的内容实际上是预期的内容,而不用担心会抛出异常。

验证是通过使用带有小型正则表达式(RegEx)的 String#matches() 方法来完成的,以确保提供的内容是数字,并且所提供的值在所需的包括无符号数字范围内,范围是从 1100。如果验证失败,用户需要重试或者输入 'Q'(或以 Q 开头的任何内容 - 不区分大小写)来退出。

Scanner input = new Scanner(System.in);
int intValue = 0;
String numberString = "";

// 提示和输入...
while (intValue == 0) {
    System.out.print("Enter a number (or 'q' to quit): --> ");
    numberString = input.nextLine().toLowerCase();
    //退出..
    if (numberString.charAt(0) == 'q') {
        System.exit(0);
    }
    // 整数(无符号 - 范围从 1 到 100)...
    else if (numberString.matches("100|[1-9][0-9]{1}?")) {
        intValue = Integer.parseInt(numberString);
    }
    else {
        System.err.println("Invalid numerical value supplied or the supplied");
        System.err.println("value is not in the inclusive range of 1 to 100!");
        System.err.println("Try Again...");
        System.err.println();
    }
}

// 在这里添加您的处理代码。
System.out.println("The value you entered is: --> " + intValue);

String#matches() 方法中使用的正则表达式的解释:

100|[1-9][0-9]{1}?

1st Alternative 100
    100 按字面意义匹配字符 100(区分大小写)

2nd Alternative [1-9][0-9]{1}?
    匹配下列列表中的一个字符 [1-9]
    1-9 在 1(索引 49)和 9(索引 57)之间的一个字符(区分大小写)
    匹配下列列表中的一个字符 [0-9]{1}?
    {1}? 量词 — 精确匹配一次(无意义的量词)
    0-9 在 0(索引 48)和 9(索引 57)之间的一个字符(区分大小写)

如果您想更改数字范围,您可能会发现 这个网站 有用。

英文:

I just thought I would throw this in here since it is another flexible alternative to accomplishing the task. It utilizes the Scanner#nextLine() method with input validation to ensure that what is supplied is actually what is expected without the worry of an exception being thrown.

Validation is done using the String#matches() method supplied with a small Regular Expression (RegEx) to insist that numerical digits are supplied and that the supplied value is within the desired inclusive unsigned numerical range of 1 to 100. If the validation fails then the User is expected to try again or enter 'Q' (or anything that starts with Q - case insensitive) to quit.

Scanner input = new Scanner(System.in);
int intValue = 0;
String numberString = &quot;&quot;;
    
// Prompt and Input...
while (intValue == 0) {
    System.out.print(&quot;Enter a number (or &#39;q&#39; to quit): --&gt; &quot;);
    numberString = input.nextLine().toLowerCase();
    //Quit..
    if (numberString.charAt(0) == &#39;q&#39;) {
        System.exit(0);  
    }
    // Integer (unsigned - Range 1 to 100)...
    else if (numberString.matches(&quot;100|[1-9][0-9]{1}?&quot;)) {
        intValue = Integer.parseInt(numberString); 
    }
    else {
        System.err.println(&quot;Invalid numerical value supplied or the supplied&quot;);
        System.err.println(&quot;value is not in the inclusive range of 1 to 100!&quot;);
        System.err.println(&quot;Try Again...&quot;);
        System.err.println();
    }
}

//Your processing code here.
System.out.println(&quot;The value you entered is: --&gt; &quot; + intValue);

Explanation for the RegEx used within the String#matches() method:

100|[1-9][0-9]{1}?

1st Alternative 100
    100 matches the characters 100 literally (case sensitive)

2nd Alternative [1-9][0-9]{1}?
    Match a single character present in the list below [1-9]
    1-9 a single character in the range between 1 (index 49) and 9 (index 57) (case sensitive)
    Match a single character present in the list below [0-9]{1}?
    {1}? Quantifier — Matches exactly one time (meaningless quantifier)
    0-9 a single character in the range between 0 (index 48) and 9 (index 57) (case sensitive)

If you want to change your numerical range then you may find this site useful.

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

发表评论

匿名网友

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

确定