2016-11-20 113 views
0

如果某人输入除数字之外的任何内容(例如“*”/“xyz”),我在查找如何显示“无效输入再见”消息时遇到问题为一个,b,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

你是什么意思?如果输入不是数字,你想打印吗? – ItamarG3

+0

在'else'内使用'hasNextDouble'和'if'以及'nextLine'来清除不需要的输入 –

回答

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块封装在循环中,进行有限或无限次重试。

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块会处理这一切。

我希望工作。

相关问题