使用户仅在扫描仪Java中输入整数 [英] Make user only input integer in scanner Java
本文介绍了使用户仅在扫描仪Java中输入整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在这里遇到一些问题.我只想用户可以输入为整数.我已经尝试了许多代码,但仍然无法正常工作.顺便说一句,这是我的代码
i have some problems here. I want to user only can input as an integer. I have tried by many code, but still doesn't work. Btw, this is my code
import java.util.Scanner;
public class test {
public static void main (String []args){
Scanner scan = new Scanner(System.in);
int number = scan.nextInt();
}
}
出现错误时,消息将显示为
When error, the message will shown as
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)
请帮助我(初级程序员);
Please help me (Beginner Programmer);
推荐答案
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();
}
此代码将检查输入是否为整数,如果为整数则将继续输入.
This code will check if the input is an Integer, if it is then it will continue.
这篇关于使用户仅在扫描仪Java中输入整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文