[英]Why does my program print out the exception statement endlessly give bad user input?
我不知道我的标题是否有意义,但这是代码©
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
它打印出invalid input
。 但是,这不是问题,而是无限打印出来。 我尝试调整try
catch
块,但它根本没有帮助
nextInt
不会从输入缓冲区中删除非整数数据,因此除非消耗了数据,否则它将无限期地回收。 在这种情况下, InputMismatchException
会抛出InputMismatchException
,因此您可以将异常块编写为
} catch (InputMismatchException e) {
System.out.println("Invalid input " + input.nextLine());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.