我是Java的新手,我正在尝试制作一个基本的计算器,我已经设法让它工作并根据需要生成一个双。我的问题是,如果用户输入错误的数据类型,我希望它提供错误消息,例如串
package com.company;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
double n1, n2;
String n3;
Scanner inp = new Scanner(System.in);
System.out.print("Enter first value: ");
String inp1 = inp.nextLine();
n1 = Double.parseDouble(inp1);
System.out.print("Enter Second Value: ");
String inp2 = inp.nextLine();
n2 = Double.parseDouble(inp2);
System.out.print("Enter Operation: ");
String inp3 = inp.nextLine();
switch (inp3) {
case "+":
System.out.println("The result is: " + (n1 + n2));
break;
case "-":
System.out.println("The result is: " + (n1 - n2));
break;
case "*":
System.out.println("The result is: " + (n1 * n2));
break;
case "/":
System.out.println("The result is: " + (n1/n2));
break;
default:
System.out.println("Invalid Operation! \nPlease use '-,+,*,/' ");
}
}
}
这是我目前的代码,我愿意接受任何建设性的批评来改进我的代码。我似乎无法找到解决问题的方法! 谢谢你的帮助:)
答案 0 :(得分:0)
public static double parseDouble(String s)
抛出NumberFormatException
抛出以指示应用程序已尝试将字符串转换为其中一种数字类型,但该字符串没有适当的格式。
因此,只需使用n1 = Double.parseDouble(inp1);
并try catch
阻止每个catch
,请打印您的错误消息。
答案 1 :(得分:0)
使用例外。
这样做,
System.out.print("Enter first value: ");
String inp1 = inp.nextLine();
try{
n1 = Double.parseDouble(inp1);
}
catch(NumberFormatException exc){
System.err.println("The input was not a valid double");
}
当parseDouble()
无法将给定的String解析为double时,它会抛出NumberFormatException
。上面的代码检查是否在try
块内抛出了这个异常并“捕获”它并处理catch
块中的异常。有关此here
详细了解例外here
答案 2 :(得分:0)
解析双打使用
try{
n2 = Double.parseDouble(inp2);
} catch(NumberFormatException numberFormatException){
System.out.println("Wrong number format of input: "+inp2+". Exception:" +numberFormatException.getMessage());
return;
}
如果您不想使用Exceptions来检查输入字符串是否为数字格式,您可以随时使用某些库,例如apache commons。在这种情况下,代码看起来像这样
if (StringUtils.isNumeric(inp2)) {
n2 = Double.parseDouble(inp2);
} else {
System.out.println("Wrong number format of input: " + inp2);
return;
}
答案 3 :(得分:0)
为简单起见,你可以有一个方法,一直要求输入,直到实现一个,例如:
public double askForDouble(Scanner input){
while(true){
System.out.println("enter a good double:" ) ;
try{
return Double.parseDouble(input.nextLine());
}catch(Exception e){
System.out.println("not a good double try again...");
}
}
}
然后在你的main方法中你可以替换
String inp1 = inp.nextLine();
n1 = Double.parseDouble(inp1);
与
n1 = askForDouble(inp);
相同的程序可以应用于您的数学运算(例如+, - ) 太
答案 4 :(得分:0)
方法parseDouble可以抛出以下例外:
您可能需要使用try / catch包围代码:
try {
String inp1 = inp.nextLine();
if(null != inp1 ) {
n1 = Double.parseDouble(inp1);
}
} catch (NumberFormatException e) {
// Handle NFE.
}
答案 5 :(得分:0)
我认为你想在输入错误后处理异常。我看到您将String
输入解析为double,在这种情况下,应该从该解析方法缓存NumberFormatException
。你可以从那里处理用户输入错误String
。
或者您使用inp.nextDouble()
从控制台读取数字,在这种情况下可能会显示InputMismatchException
,您可以处理此异常。