如果有人为a,b的值输入除数字以外的任何内容(例如“*”/“xyz”),我在查找如何显示“无效输入Good bye”消息时遇到问题c在我制作的二次计算器中
DecimalFormat df = new DecimalFormat("0.00#");
Scanner sc = new Scanner(System.in);
Double a,b,c;
System.out.println("Welcome to the Grand Quadratic Calculator ! ");
System.out.print("Enter value of a = ");
a = sc.nextDouble();
System.out.print("Enter value of b = ");
b = sc.nextDouble();
System.out.print("Enter value of c = ");
c = sc.nextDouble();
double xone = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 * a;
double xtwo = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 * a;
if(b * b - 4 * a * c >= 0)
{
System.out.println("x1 = " + df.format(xone));
System.out.print("x2 = " + df.format(xtwo));
}
else
System.out.print("Invalid Input. \nGood Bye.");
答案 0 :(得分:1)
当用户输入无效输入时,sc.nextDouble()
会抛出InputMismatchException
。
这将使您当前的程序崩溃,
代码打印"无效输入"永远不会到达消息。
您可以将代码包装在try
块中,并捕获此异常:
try {
System.out.print("Enter value of a = ");
a = sc.nextDouble();
// ...
} catch (InputMismatchException e) {
System.out.print("Invalid Input. \nGood Bye.");
// return or exit with failure
}
"再见"消息建议您要退出无效输入。
如果您实际上并不想退出,那么您可以在循环中包装用户输入部分和try-catch块,重试次数有限或无限制。
答案 1 :(得分:0)
为了引导用户输入错误,你应该将输入语句和所有算术运算放入try .... catch块。
尝试以下代码:
DecimalFormat df = new DecimalFormat("0.00#");
Scanner sc = new Scanner(System.in);
Double a,b,c;
System.out.println("Welcome to the Grand Quadratic Calculator ! ");
System.out.print("Enter value of a = ");
try { //this line will disallowing the program from terminating when the users inputs an invalid value
a = sc.nextDouble();
System.out.print("Enter value of b = ");
b = sc.nextDouble();
System.out.print("Enter value of c = ");
c = sc.nextDouble();
double xone = (-b + Math.sqrt(b * b - 4 * a * c)) / 2 * a;
double xtwo = (-b - Math.sqrt(b * b - 4 * a * c)) / 2 * a;
if(b * b - 4 * a * c >= 0)
{
System.out.println("x1 = " + df.format(xone));
System.out.print("x2 = " + df.format(xtwo));
}
}
catch(InputMismatchException err){
System.out.println("Invalid Input. \nGood Bye.");
}
else语句已被删除,catch块将处理所有这些。
我希望这有效。