gpt4 book ai didi

java - 在无限循环中抛出异常。找不到我的出路。

转载 作者:行者123 更新时间:2023-12-01 23:30:01 26 4
gpt4 key购买 nike

当抛出 InputMismatchException 时,我进入了一个无限循环,我一生都无法弄清楚为什么。基本上,该程序的主要目标是针对用户输入的负数引发异常,并确保用户实际输入一个整数(而不是像“r45”这样的东西)。任何帮助将不胜感激。谢谢。

  import java.util.*;

public class conversion{
static Scanner in = new Scanner (System.in);
static final double centimeters_per_inch = 2.54;
static final int inches_per_foot = 12;

public static void main (String [] args){
int feet;
int inches;
int totalInches;
double centimeters;
boolean done = false;
do{
try
{
System.out.print("Enter feet: ");
System.out.flush();
feet = in.nextInt();
System.out.println();
System.out.print("Enter inches: ");
System.out.flush();
inches = in.nextInt();

if (feet < 0 || inches < 0)
throw new NonNegative();

System.out.println();

done = true;
System.out.println("The numbers you entered are " + feet +" feet and " + inches+ " inches");
totalInches = inches_per_foot * feet + inches;
System.out.println();
System.out.println("The total number of inches = " + totalInches);
centimeters = totalInches * centimeters_per_inch;
System.out.println("The number of centimeteres = " + centimeters);
}

catch (NonNegative a){
System.out.println(a.toString());
}
catch(InputMismatchException e) {
System.out.println("This is not a number");
}
}while(!done);
}

}

最佳答案

当发生 InputMismatchException 时,来自 Scanner 的无效输入将通过 while 循环发回,并重复该过程无限。。调用 nextLine 以使用来自 Scanner 的非数字输入。这将防止未使用的数据被发送回循环

System.out.println("This is not a number " + in.nextLine());

关于java - 在无限循环中抛出异常。找不到我的出路。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19471908/

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