java 使用扫描仪时清除输入缓冲区
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29590003/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Clearing input buffer when using a Scanner
提问by ANUPAM CHANDA
I have a java code, and there I want to take an integer from user. If that input is an integer really then its fine the control will go through next, but if the input is other than an integer the control will go for the scanning again. The problem is when other than an integer is being given by user the while loop is being looped again and again. How to solve? Please help me out.
我有一个 java 代码,我想从用户那里获取一个整数。如果该输入确实是一个整数,那么它可以很好地控制下一步,但如果输入不是整数,则控制将再次进行扫描。问题是当用户给出的不是整数时,while 循环会一次又一次地循环。怎么解决?请帮帮我。
I have tried the question answer in this site but have not got any result.
我已经尝试过这个网站上的问题答案,但没有得到任何结果。
Here is my code-
这是我的代码-
import java.io.* ;
import java.util.Scanner;
class A{
int name;
int take_int(){
Scanner data=new Scanner(System.in);
//BufferedWriter BW=new BufferedWriter();
while(true){
int fault_res=0 ;
try{
System.out.print("Enter A Number : ");
//BW.flush();
name=data.nextInt(); // comment : if user give an alphabet
// then the control rounds again and
// again, how to solve? System is not
// taking any input after entering
// any alphabet first time, but it
// should take as per my code, I
// think is is happening due to i/p
// buffer, unable to delete it.
}
catch(Exception E){
System.out.println("\nSomething Went Wrong !!\nRetry Please !!!");
fault_res=1 ;
}
if(fault_res==0){break ;}
}
System.out.println("\nnumber at other class "+name);
return name ;
}
}
class sn{
public static void main(String args[]){
A obA=new A();
int number=obA.take_int();
System.out.println("\nYou have entered "+number);
}
}
回答by Nirmal
You can clear the input from catch block. If you do not want anything other than integer then just do inputStream.nextLine();
in your catch
block.
您可以清除 catch 块的输入。如果你不想要整数以外的任何东西,那么就inputStream.nextLine();
在你的catch
块中做。
Here is a generic snippet for taking only integer input.
这是一个仅采用整数输入的通用代码段。
private static int takeOnlyIntegerInput() {
Scanner keyboard = new Scanner(System.in);
boolean isValid = false;
int num=-1;
while (isValid == false) {
System.out.print("Please enter an: ");
try {
num = keyboard.nextInt();
isValid = true;
} catch (InputMismatchException ex) {
System.out.println("Wrong input. Ony integer input will be processed.");
//clean up the garbage input
keyboard.nextLine();
}finally{
keyboard.close();
}
}
return num;
}
回答by RealSkeptic
You should add, in your exception's catch
clause, either data.next()
or data.nextLine()
.
您应该在例外catch
条款中添加data.next()
或data.nextLine()
。
Which of them to choose depends on the sort of input and what kind of mistakes you expect. If you expect more input on the same line, for example:
选择哪一个取决于输入的类型和您期望的错误类型。如果您希望在同一行上有更多输入,例如:
XXXX 1234 5678
then only data.next()
will work correctly, because it will skip the XXXX
and the next token will be 1234
which is what you want.
那么只会data.next()
正常工作,因为它将跳过XXXX
并且下一个令牌将1234
是您想要的。
If you use data.nextLine()
in this case, then both XXXX
and 1234
will be skipped - everything until the end of the line, and the next token to be read will be 5678
.
如果data.nextLine()
在这种情况下使用,则XXXX
和1234
都将被跳过 - 直到行尾的所有内容,下一个要读取的标记将为5678
.
回答by Blip
Rewrite your program as follows and it will work.
如下重写你的程序,它会起作用。
import java.io.* ;
import java.util.Scanner;
class A{
int name;
int take_int(){
Scanner data=new Scanner(System.in);
while(true){
int fault_res=0 ;
try{
System.out.print("Enter A Number : ");
String input = data.nextLine();
name=Integer.parseInt(input);
}
catch(Exception E){
System.out.println("Something Went Wrong !! Retry Please !!!");
fault_res=1 ;
}
if(fault_res==0){break ;}
}
System.out.println("\nnumber at other class "+name);
return name ;
}
}
class sn{
public static void main(String args[]){
A obA=new A();
int number=obA.take_int();
System.out.println("\nYou have entered "+number);
}
}