gpt4 book ai didi

java - 如何在 Java 中的 try catch 中获取异常?

转载 作者:行者123 更新时间:2023-11-30 07:25:01 25 4
gpt4 key购买 nike

所以我正在编写一个程序,我想要一个异常(exception),这样程序就不会崩溃。
如果用户输入的字符串不在 else if 语句 中,则不会崩溃。

此外,我尝试对整数执行此操作,因此如果有人尝试编写非整数的内容,它不会崩溃。程序会捕获它并指出它不是整数

如何在 java 中的 try catch 中获取异常。

感谢您的帮助

代码如下:

import java.util.InputMismatchException;
import java.util.Scanner;


public class WeightOnADifferentPlanet {
public static void main ( String[] args ){
Scanner scan = new Scanner ( System.in );


System.out.println("Where do you want to travel:?");
try{
String planetName = scan.nextLine();
}
catch(/*need help here*/){
System.out.println("Please check your spelling");
}



System.out.println("Please enter your weight:");
try{
int weight = scan.nextInt();
}
catch(InputMismatchException e)
{
System.out.println("That is not an integer");
}
double earthCalculation = weight * 1.0;
double jupiterCalculation = weight * (21.0 / 8.0); //check
double marsCalculation = weight * (3.0 / 8.0);
double mercuryCalculation = weight * (3.0 / 10.0);
double neptuneCalculation = weight * (11.0 / 10.0); //check
double plutoCalculation = weight * (7.0 / 10.0);
double saturnCalculation = weight * (6.0 / 5.0); //check
double uranusCalculation = weight * (9.0 / 10.0);
double venusCalculation = weight * (7.0 / 8.0);


if (planetName.equalsIgnoreCase("Earth"))
{
System.out.println("Your weight on "+planetName+" is: "+earthCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Jupiter"))
{
System.out.println("Your weight on "+planetName+" is: "+jupiterCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Mars"))
{
System.out.println("Your weight on "+planetName+" is: "+marsCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Mercury"))
{
System.out.println("Your weight on "+planetName+" is: "+mercuryCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Neptune"))
{
System.out.println("Your weight on "+planetName+" is: "+neptuneCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Pluto"))
{
System.out.println("Your weight on "+planetName+" is: "+plutoCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Saturn"))
{
System.out.println("Your weight on "+planetName+" is: "+saturnCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Uranus"))
{
System.out.println("Your weight on "+planetName+" is: "+uranusCalculation+" pounds.");
}
else if (planetName.equalsIgnoreCase("Venus"))
{
System.out.println("Your weight on "+planetName+" is: "+venusCalculation+" pounds.");

}


}
}
}

最佳答案

我相信 scan.nextInt(); 无论如何都只会扫描整数,因此不需要捕获非整数

关于java - 如何在 Java 中的 try catch 中获取异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36927877/

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