如何解决如何除双精度和整数
我创建了这个简单的计算器。我的问题是,如果有人输入一个双精度值,它将导致系统崩溃。我该如何使异常并使之也排除双精度值呢?
public class Main {
public static void main(String[] args) {
double variable ;
System.out.println("input your first number");
Scanner scan = new Scanner(System.in);
int number1 = scan.nextInt();
System.out.println("input your second number");
Scanner scan2 = new Scanner(System.in);
int number2 = scan2.nextInt();
int result = number1*number2;
System.out.println(result);
}
}
解决方法
double number1;
double number2;
try {
System.out.println("input your first number");
Scanner scan = new Scanner(System.in);
String string1 = scan.nextLine();
number1 = Double.parseDouble(string1);
System.out.println("input your second number");
String string2 = scan.nextLine();
number2 = Double.parseDouble(string2);
} catch (NumberFormatException e) {
System.out.println("Invalid number");
return;
}
double result = number1 * number2;
System.out.println(result);
,
您可以使用 try + catch 块来捕获异常,并进行相应的处理。
try
语句使您可以定义一个代码块,该代码块在执行时将进行错误检查。
如果try块中发生错误,则catch
语句允许您定义要执行的代码块。
try
和catch
关键字成对出现。例如:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
在这种情况下,插入双精度字会引发 NumberFormatException ,这是在无法正确格式化整数时抛出的异常。
这就是您的代码应该是的:
public class Main {
public static void main(String[] args) {
try{
double variable ;
System.out.println("input your first number");
Scanner scan = new Scanner(System.in);
int number1 = scan.nextInt();
System.out.println("input your second number");
Scanner scan2 = new Scanner(System.in);
int number2 = scan2.nextInt();
int result = number1*number2;
System.out.println(result);
}catch(NumberFormatException e){
System.out.println("Invalid integer")
}
}
}
...或者您可以将其视为双人间。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。