Search code examples
javainputprogram-entry-point

How to call a java main function?


public class Calculator {
    public static void main(String[] args) {
        if (args.length < 3) {
            System.out.println("Usage: java Calculator operand1 operator operand2");
            System.exit(0);
        }
        int result = 0;
        switch (args[1].charAt(0)) {
        case '+':
            result = Integer.parseInt(args[0]) + Integer.parseInt(args[1]);
            break;
        case '-':
            result = Integer.parseInt(args[0]) - Integer.parseInt(args[1]);
            break;
        case '*':
            result = Integer.parseInt(args[0]) * Integer.parseInt(args[1]);
            break;
        case '/':
            result = Integer.parseInt(args[0]) / Integer.parseInt(args[1]);
            break;
        }
        System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
    }
}

When I ran Calculator.java in terminal, I tried a few ways like this:

Rasperry:src maggiesmac$ javac Calculator.java
Rasperry:src maggiesmac$ java Calculator 1+2
Usage: java Calculator operand1 operator operand2
Rasperry:src maggiesmac$ java Calculator 1 + 2
Exception in thread "main" java.lang.NumberFormatException: For input string: "+"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:572)
    at java.lang.Integer.parseInt(Integer.java:615)
    at Calculator.main(Calculator.java:15)
Rasperry:src maggiesmac$ java Calculator.main(1,+,2)
-bash: syntax error near unexpected token `('

So how can I call the Java main() method? How should I pass the parameters to it?


Solution

  • Please change the index in the case structure (as suggested by @SotiriosDelimanolis). Also, we can use String in case:

    public class Calculator {
        public static void main(String[] args) {
            if (args.length < 3) {
                System.out.println("Usage: java Calculator operand1 operator operand2");
                System.exit(0);
            }
            int result = 0;
            switch (args[1]) {
            case "+":
                result = Integer.parseInt(args[0]) + Integer.parseInt(args[2]);
                break;
            case "-":
                result = Integer.parseInt(args[0]) - Integer.parseInt(args[2]);
                break;
            case "*":
                result = Integer.parseInt(args[0]) * Integer.parseInt(args[2]);
                break;
            case "/":
                result = Integer.parseInt(args[0]) / Integer.parseInt(args[2]);
                break;
            }
            System.out.println(args[0] + ' ' + args[1] + ' ' + args[2] + " = " + result);
        }
    }