您好,我是Java初学者。我想制作一个采用1到9之间的整数的方法。我正在使用异常处理程序,以便它可以处理错误或不匹配的输入,但似乎只执行语句“choice”。 = input.nextInt()”一次,因此我的循环进入了无限。
代码如下:
import java.util.*;
public class Player{
private int[] over;
private int choice;
private int coordinates[];
private static Scanner input = new Scanner(System.in);
public Player(){
over = new int[5];
for(int i = 0; i < 5; i++){
over[i] = 1;
}
coordinates = new int[2];
coordinates[0] = coordinates[1] = -1;
}
public void getChoice(){
int choice = -1;
boolean inputIsOk;
do{
System.out.print("Enter Your Choice: ");
inputIsOk = true;
try{
choice = input.nextInt();
}
catch(InputMismatchException e){
System.out.println("Invalid choice");
inputIsOk = false;
}
if(choice < 1 || choice > 9){
System.out.println("Enter Choice In Range(1-9)");
inputIsOk = false;
}
}while(!inputIsOk);
System.out.println("You Entered "+choice);
}
}
这是测试类:
public class TestPlayer{
public static void main(String args[]){
Player p1 = new Player();
p1.getChoice();
}
}
输出是:
第一种情况当仅输入积分选择时
harsh@harsh-Inspiron-3558:~/java/oxgame$ javac TestPlayer.java
harsh@harsh-Inspiron-3558:~/java/oxgame$ java TestPlayer
Enter Your Choice: 10
Enter Choice In Range(1-9)
Enter Your Choice: -1
Enter Choice In Range(1-9)
Enter Your Choice: 55
Enter Choice In Range(1-9)
Enter Your Choice: 5
You Entered 5
其次,当我输入错误的输入时:
Enter Your Choice: 10
Enter Choice In Range(1-9)
Enter Your Choice: 55
Enter Choice In Range(1-9)
Enter Your Choice:g
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
Enter Your Choice: Invalid choice
Enter Choice In Range(1-9)
and it goes on....
请帮助我,谢谢。
最佳答案
这会工作
try{
choice = Integer.parseInt(input.next());
}
catch(NumberFormatException e){
System.out.println("Invalid choice");
inputIsOk = false;
}
原因是:
说扫描程序从流中读取一个对象,说
typeCache
。直到不会获得整数值,缓冲区才会被刷新,并且typeCache
将保存String
,直到使用next()
(或任何等效方法)读取它为止。Scanner
类的代码: public int nextInt() {
return nextInt(defaultRadix);
}
public int nextInt(int radix) {
// Check cached result
if ((typeCache != null) && (typeCache instanceof Integer)
&& this.radix == radix) {
int val = ((Integer)typeCache).intValue();
useTypeCache();
return val;
}.......
要么
只需在您的catch块中添加
input.next();
,它将自动清除typeCache
。