Exception in thread "main" java.lang.NumberFormatException: For input string: "volume" Error

78 Views Asked by At

I am working on a calculator which will calculate the volume or surface area of a sphere depending on what the input arguments are.

When I input "sphere volume 5" it throws a Exception in thread "main" java.lang.NumberFormatException: For input string: "volume" Error. Can someone help point out what is causing this error?

Thanks

public class SimpleCalculator {
    public static void main(String[] args) {
        String operator = args[0];
        int num1 = Integer.parseInt(args[1]);
        int num2 = Integer.parseInt(args[2]);
        double result;

        switch (operator) {
            case "+" :
                result = num1 + num2;
                System.out.println(result);
                break;
            
            case "-" :
                result = num1 - num2;
                System.out.println(result);
                break;

            case "*" :
                result = num1 * num2;
                System.out.println(result);
                break;
            
            case "/" :
                double dnum1 = num1;
                result = dnum1 / num2;
                System.out.println(result);
                break;
            
            case "sphere" :
            
            if (args[1] == "volume") {
                result = (4.0/3)* Math.PI * Math.pow(num2, 3);
                System.out.println(result);
                break;
            } else if (args[1] == "surface"){
                result = 4.0 * Math.PI * Math.pow(num2, 2);
                System.out.println(result);
                break;
            }
            break;
        }
        
    }

}

I initially had a String variable calcType to differentiate between "volume" and "surface" but I assumed doing that would be redundant as the args are Strings to begin with. This was my initial code:

            case "sphere" :
            String calcType = args[1];
            if (calcType.equals("volume")) {
                result = (4.0/3)* Math.PI * Math.pow(num2, 3);
                System.out.println(result);
                break;
            } else if (calcType.equals("surface")){
                result = 4.0 * Math.PI * Math.pow(num2, 2);
                System.out.println(result);
                break;
            }
            break;
1

There are 1 best solutions below

0
Althaen On

If your inputs are "sphere" "volume" and "5" then since the first index of an array is 0 your args array will be like:

args[0] = "sphere";
args[1] = "volume";
args[2] = "5";

The problem is that when you parse args[1] into an integer you are trying to turn the string "volume" into a number when "volume" is not a number. As the exception you are getting is telling you.