用户错误后返回扫描仪读取 - java [英] Back scanner reading after user error - java

查看:79
本文介绍了用户错误后返回扫描仪读取 - java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读过的用户输入必须只是int类型,当用户输入字母而不是int时会出现问题。我知道如何处理异常,但我想将扫描器读回到用户犯了错误的位置。我能怎么做?
我已尝试使用无限循环,但它不起作用。

I have read user input that must be only of type int, the problem comes when the user enters letter instead of a int. I know how to handle the exception, but I would like to return the scanner read where the user has made a mistake. How can I do? I already tried with an infinite loop, but it does not work.

try{
    System.out.print("enter number: ");
    value = scanner.nextInt();
}catch(InputMismatchException e){
    System.err.println("enter a number!");
}


推荐答案

虽然其他答案给你正确想要使用循环,你应该避免使用异常作为基本逻辑的一部分。相反,您可以使用扫描程序中的 hasNextInt 来检查用户是否传递了整数。

While other answers give you correct idea to use loop you should avoid using exceptions as part of your basic logic. Instead you can use hasNextInt from Scanner to check if user passed integer.

System.out.print("enter number: ");
while (!scanner.hasNextInt()) {
    scanner.nextLine();// consume incorrect values from entire line
    //or 
    //tastiera.next(); //consume only one invalid token
    System.out.print("enter number!: ");
}
// here we are sure that user passed integer
int value = scanner.nextInt();

这篇关于用户错误后返回扫描仪读取 - java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆