gpt4 book ai didi

java - 循环逻辑中的漏洞

转载 作者:行者123 更新时间:2023-12-02 05:07:34 25 4
gpt4 key购买 nike

我正在尝试一个异常处理程序来计算以厘米为单位的高度。

import java.util.*;
class Ex{
private static double height(int feet, int inches) throws Exception{
if(feet < 0 || inches < 0)
throw new Exception("Please enter positive values only.");
return (feet * 30.48) + (inches * 2.54);
}

public static void main(String args[]){
Scanner scanner=new Scanner(System.in);
boolean continueLoop = true;

do{
try
{
System.out.println("Enter height in feet:");
int feet=scanner.nextInt();
System.out.println("and in inches:");
int inches = scanner.nextInt();
double result = height(feet,inches);
System.out.println("Result:"+result+" cm");
continueLoop = false;
}
catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
}
catch(Exception e){
System.out.println(e.getMessage());
}
}while(continueLoop);
}
}

当发生InputMismatchException时,程序进入无限循环。我这里的逻辑有什么问题吗?我应该做什么改变?

最佳答案

您应该将 scanner.nextLine() 添加到您的 catch block 中,以便消耗当前行的其余部分,以便 nextInt 可以尝试读取新输入从下一行开始。

 do{
try
{
System.out.println("Enter height in feet:");
int feet=scanner.nextInt();
System.out.println("and in inches:");
int inches = scanner.nextInt();
double result = height(feet,inches);
System.out.println("Result:"+result+" cm");
continueLoop = false;
}
catch(InputMismatchException e){
System.out.println("You must enter integers. Please try again.");
scanner.nextLine();
}
catch(Exception e){
System.out.println(e.getMessage());
scanner.nextLine();
}
}while(continueLoop);

关于java - 循环逻辑中的漏洞,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27637309/

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