首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >InputMismatchException仍在显示

InputMismatchException仍在显示
EN

Stack Overflow用户
提问于 2022-04-08 13:18:16
回答 1查看 53关注 0票数 -2

我想让java给我一个随机数,用户会试图猜测它,如果用户试图输入无效的数据类型,它会说:“无效输入。整数。再试一次”,然后继续代码,但是代码在显示消息后没有推入,即使它有while循环。

我的全部杂务:

代码语言:javascript
复制
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--; 
        }
    }   
}   

}

代码语言:javascript
复制
    class InvalidInputException extends Exception {
        InvalidInputException(){
        super();
}       

}

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-04-08 14:23:23

根据java规范在扫描仪上的应用

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

nextInt()则这样做:

将输入的下一个令牌扫描为int。

因此,包含空白的输入将被视为多个输入,这些输入可能不像预期的那样工作。

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

代码语言:javascript
复制
try
{
    String ln = sc.nextLine();
    userInput = Integer.parseInt(ln);
    
    ...
}
catch (InputMismatchException | NumberFormatException im)
{...}
catch (InvalidInputException iie)
{...}

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

代码语言:javascript
复制
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--;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71797745

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档