让计算器检查数据类型并输出消息?

Make calculator check data-type and output a message?

我真的是 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 '-,+,*,/' ");

    }

}

}

这是我目前的代码,我愿意接受任何建设性的批评来改进我的代码。我似乎无法找到解决问题的方法! 感谢您的帮助:)

parseDouble:

public static double parseDouble(String s)

抛出 NumberFormatException

Thrown to indicate that the application has attempted to convert a string to one of the numeric types, but that the string does not have the appropriate format.

所以只需用 try catch 包围每个 n1 = Double.parseDouble(inp1); 并在 catch 块中打印错误消息。

使用例外。

这样做,

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() 无法将给定的字符串解析为双精度值时,它会抛出一个 NumberFormatException。上面的代码检查此异常是否在 try 块内抛出并 "catch"s 它并处理 catch 块中的异常。有关此内容的更多信息 here

了解有关异常的更多信息here

  1. 不要使用 n1、n2、n3 等变量名。在较大的项目中,这会使您感到困惑。
  2. 在解析双打时使用

    try{
        n2 = Double.parseDouble(inp2);
    } catch(NumberFormatException numberFormatException){
        System.out.println("Wrong number format of input: "+inp2+". Exception:" +numberFormatException.getMessage());
        return;
    }
    
  3. 如果您不想使用异常来检查输入字符串是否为数字格式,您始终可以使用一些库,例如 apache commons。在这种情况下,代码将如下所示

    if (StringUtils.isNumeric(inp2)) {
        n2 = Double.parseDouble(inp2);
    } else {
        System.out.println("Wrong number format of input: " + inp2);
        return;
    }
    

这里有更多信息:How to check if a String is numeric in Java

为简单起见,您可以使用一种方法不断请求输入,直到获得正确的输入,例如:

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...");

   }
  }
}

然后在你的主要方法中你可以替换

String inp1 = inp.nextLine();
n1 = Double.parseDouble(inp1);

n1 = askForDouble(inp);

可以对您的数学运算应用相同的程序(例如 + 、 - ) 太

方法parseDouble可以抛出以下异常:

  1. NullPointerException - 如果字符串为 null
  2. NumberFormatException - 如果字符串不包含可解析的双精度数。

您可能需要用 try/catch 包围您的代码,例如:

try {
      String inp1 = inp.nextLine();
      if(null != inp1 ) {
         n1 = Double.parseDouble(inp1);
      }
} catch (NumberFormatException e) {
    // Handle NFE.
}

我想你想在输入错误后处理异常。我看到您将 String 输入解析为双精度,在这种情况下,应该从该解析方法中缓存 NumberFormatException。您可以从那里处理用户输入错误 String.

的情况

或者你使用inp.nextDouble()从控制台读取数字,在这种情况下可能会出现InputMismatchException,你可以处理这个异常。