gpt4 book ai didi

java - 为什么我的程序会无休止地打印异常语句,给出错误的用户输入?

转载 作者:行者123 更新时间:2023-11-30 03:21:11 24 4
gpt4 key购买 nike

我不知道我的标题是否有意义,但这是代码©

import java.util.InputMismatchException;
import java.util.Scanner;
public class Gussing {
public static void theGame(Scanner input){
int randomNum= (int)(Math.random()*101);//randomizes a number between 0-100 inclusive of both
System.out.println(randomNum); //for debugging purposes
int attemptCounter = 0; //counts how many attempts the user make
System.out.print("Welcome to the guess-the number game! Enter your guess: ");

while(true){
System.out.println("here is bad input");
try{
System.out.println("here is after the bad input");
int userInput= input.nextInt();
if (userInput==randomNum) //when usr input and generated random number are equal we print how many attempts
{
attemptCounter++;
System.out.println("Congrats you made the right guess after "+ attemptCounter + " attempts!");
break;

}

if(userInput<randomNum){
attemptCounter++;
System.out.print("Too low! Try again: ");

}
else {
attemptCounter++; //else clause does the opposite of if clause
System.out.print("Too high! Try again: ");

}


}
catch( Exception e){
System.out.println("Invalid input");

}
}

}
public static void main(String[] args){
Scanner input = new Scanner (System.in);
theGame (input);


System.out.println("Play again? (Y/N)");

try{
char answer=input.next().toLowerCase().charAt(0);



//toLowerCase method so that N =n = no !

if (answer =='y') theGame (input);


else if (answer =='n') System.out.println("Good bye");


input.close(); //no more input data

}
catch(Exception e){
System.out.println("invalid input");
}
}


}

因此,当用户输入错误类型(即不是 int)时,它会打印出无效输入。然而,这不是问题,问题是它无限地打印出来。我尝试调整 try catch block ,但根本没有帮助

最佳答案

nextInt 不会从输入缓冲区中删除非整数数据,因此除非数据被消耗,否则它会无限期地回收。在这种情况下,该方法会抛出 InputMismatchException,因此您可以将异常 block 编写为

} catch (InputMismatchException e) {
System.out.println("Invalid input " + input.nextLine());
}

关于java - 为什么我的程序会无休止地打印异常语句,给出错误的用户输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31302784/

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