我这里有一些问题。我想用户只能作为一个整数输入。我尝试过许多代码,但仍然不起作用。顺便说一下,这是我的密码
import java.util.Scanner;
public class test {
public static void main (String []args){
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
}
}错误时,该消息将显示为
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at test.main(test.java:6)请帮助我(初级程序员);
发布于 2016-09-04 12:04:41
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while (!scan.hasNextInt()) {
System.out.println("Input is not a number.");
scan.nextLine();
}
int number = scan.nextInt();
}此代码将检查输入是否为Integer,如果是,则将继续。
发布于 2016-09-04 12:00:59
试试这个:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (true) {
System.out.print("Enter a number -> ");
String input = sc.next();
int intInputValue = 0;
try {
intInputValue = Integer.parseInt(input);
break;
} catch (NumberFormatException ne) {
System.out.println("This is not a number");
}
}
}当用户输入整数输入值时,此程序将结束。
输出

发布于 2016-09-04 12:10:20
只有在用户没有输入integer.For的情况下才会发生这样的错误,您可以创建一个try-catch块来捕获异常,如下所示:
String input = sc.next();
int number = 0;
try {
number = Integer.valueOf(input);
} catch (NumberFormatException ne) {
System.out.println("Invalid input!");
}为了更好地优化解决方案,将所有这些都放在一个循环中,并在try-block中打破它,如果用户输入一个错误的数字,则继续轮询输入。
https://stackoverflow.com/questions/39316625
复制相似问题