gpt4 book ai didi

java - 导致无限循环的异常处理(java)

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:48 24 4
gpt4 key购买 nike

你好,我是 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....

请帮助我,谢谢。

最佳答案

如果你改变 catch 子句如下:

} catch (InputMismatchException e) {
input.next();
System.out.println("Invalid choice");
inputIsOk = false;
}

这会起作用,input.next(); 我不知道为什么,旧代码 - 当你输入 g - 只是执行这个 choice = input.nextInt(); 就好像它仍然保持相同的值一样,它没有等待用户输入,调用 next () 解决了这个问题。

关于java - 导致无限循环的异常处理(java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45529603/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com