InputMismatchException仍显示

发布于 2025-01-19 23:28:28 字数 1502 浏览 0 评论 0原文

我希望java给我随机数,用户会尝试猜测它,如果用户尝试输入无效的数据类型,它会说:“无效输入。仅整数。再试一次”并将继续代码,但是代码即使它有 while 循环,在显示消息后也不会推送。

编辑:我使用了 next();而不是 nextInt();它修复了我的代码

我的整个chode:

import java.util.*;
public class tine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random ranNum = new Random();
boolean Win = false;
int nAttempt = 0;
int number = (int)(Math.random()*50 );

int userInput;
System.out.println("Guess a number from 1-50!");    
while (Win == false) {
nAttempt++;
try {       
    userInput = sc.nextInt();
    if (userInput < number && userInput >= 1) {
        System.out.println("too low.");
}
    else if (userInput > number && userInput <= 50){
        System.out.println("too high"); 
}
    else if (userInput == number) {
        System.out.println("you got it right in " +nAttempt +" attemp(s)"); 
        Win = true;     
}
    else {
        throw new InvalidInputException();
        
    }
}   
    catch (InputMismatchException im) {
        System.out.println("Invalid Input. Integer only. Try Again");
        userInput = sc.nextInt();
        nAttempt--;
    
}
    catch (InvalidInputException iie) {
        System.out.println("Number is out of range. Try Again.");
        userInput = sc.nextInt();
        nAttempt--; 
        }
    }   
}   

}

    class InvalidInputException extends Exception {
        InvalidInputException(){
        super();
}       

}

I want java to give me random number and user will try to guess it, if the user tries to enter an invalid data type, it will say: "Invalid Input. Integer only. Try Again" and will continue the code, but the code is not pushing through after showing the message even though it has while loop.

edit: I used next(); instead of nextInt(); and it fixed my code

My whole chode:

import java.util.*;
public class tine {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Random ranNum = new Random();
boolean Win = false;
int nAttempt = 0;
int number = (int)(Math.random()*50 );

int userInput;
System.out.println("Guess a number from 1-50!");    
while (Win == false) {
nAttempt++;
try {       
    userInput = sc.nextInt();
    if (userInput < number && userInput >= 1) {
        System.out.println("too low.");
}
    else if (userInput > number && userInput <= 50){
        System.out.println("too high"); 
}
    else if (userInput == number) {
        System.out.println("you got it right in " +nAttempt +" attemp(s)"); 
        Win = true;     
}
    else {
        throw new InvalidInputException();
        
    }
}   
    catch (InputMismatchException im) {
        System.out.println("Invalid Input. Integer only. Try Again");
        userInput = sc.nextInt();
        nAttempt--;
    
}
    catch (InvalidInputException iie) {
        System.out.println("Number is out of range. Try Again.");
        userInput = sc.nextInt();
        nAttempt--; 
        }
    }   
}   

}

    class InvalidInputException extends Exception {
        InvalidInputException(){
        super();
}       

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

咽泪装欢 2025-01-26 23:28:28

根据 Scanner 上的 Java API 规范

扫描器使用分隔符模式将其输入分解为标记,默认情况下与空格匹配。

nextInt() 则执行以下操作:

将输入的下一个标记扫描为 int。

因此,包含空格的输入将被视为多个输入,这可能无法按预期工作。

为了解决这个问题,我建议使用 Scanner.nextLine() 扫描整行,它“返回当前行的其余部分,不包括末尾的任何行分隔符”;
使用 Integer.parseInt(String) 将该行解析为整数,这会在非法模式上抛出运行时异常 NumberFormatException,因此最好将其包含在 catch 语句中:

try
{
    String ln = sc.nextLine();
    userInput = Integer.parseInt(ln);
    
    ...
}
catch (InputMismatchException | NumberFormatException im)
{...}
catch (InvalidInputException iie)
{...}

然后 我没有看到在 catch 块内读取 userInput 的意义,因为当 while 循环的另一个周期开始时,它将在 try 块的第一行再次更新。因此我建议删除它们:

catch (InputMismatchException im)
{
    System.out.println("Invalid Input. Integer only. Try Again");
    // userInput = sc.nextInt();
    nAttempt--;                               
}
catch (InvalidInputException iie)
{
    System.out.println("Number is out of range. Try Again.");
    // userInput = sc.nextInt();
    nAttempt--;
}

According to java API specification on Scanner:

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace.

While nextInt() does:

Scans the next token of the input as an int.

Therefore, an input including white spaces will be regarded as multiple inputs, which may not be working as expected.

To fix this, I would suggest scanning the entire line using Scanner.nextLine(), which "returns the rest of the current line, excluding any line separator at the end";
then parse the line as an integer with Integer.parseInt(String), which throws runtime exception NumberFormatException on illegal patterns, so might as well include that in the catch statement:

try
{
    String ln = sc.nextLine();
    userInput = Integer.parseInt(ln);
    
    ...
}
catch (InputMismatchException | NumberFormatException im)
{...}
catch (InvalidInputException iie)
{...}

Also I'm not seeing the point of reading userInput inside the catch block, as it will be updated again at the first line of the try block, as another cycle of the while loop begins. Hence I suggest removing them:

catch (InputMismatchException im)
{
    System.out.println("Invalid Input. Integer only. Try Again");
    // userInput = sc.nextInt();
    nAttempt--;                               
}
catch (InvalidInputException iie)
{
    System.out.println("Number is out of range. Try Again.");
    // userInput = sc.nextInt();
    nAttempt--;
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文