我刚刚开始用java编写一个二十一点游戏。我试图让程序要求用户再次输入,如果他们输入的现金不是有效的整数。我看到很多带有 catch 的 try 语句的示例,但它们都不起作用。程序给出错误 InputMismatchException 无法解析为类型。我关注的一个线程是这个,我有完全相同的代码,只是变量名不同。这里是。 Java InputMismatchException
这是我的代码:
Scanner input_var=new Scanner(System.in);
System.out.println("Welcome to BlackJack!");
System.out.println("Enter how much money you will start with");
System.out.println("Starting cash must be whole number");
int money=0;
do{
try{
System.out.println("Enter how much money you will start with: ");
money=input_var.nextInt();
}
catch (InputMismatchException e){
System.out.println("Sry, not a valid integer");
input_var.nextInt();
}
input_var.nextLine();
}while (money<=0);
任何有关为什么我的几乎精确的代码无法工作的帮助将不胜感激。感谢您的时间和精力。
最佳答案
使用input.next()
使用,因为input.nextInt()
不存在。这就是异常的全部要点。
do{
try{
System.out.println("Enter how much money you will start with: ");
money=input_var.nextInt();
}catch (InputMismatchException e){
System.out.println("Sry, not a valid integer");
input_var.next();
}
}while (money<=0);
关于Java-Try 和 Catch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44055526/