Java main method arguments

Introduction

The following code shows how to use Java main method to create a calculator.

The program performs arithmetic operations on integers.

The program receives an expression in one string argument.

The expression consists of an integer followed by an operator and another integer.

For example, to add two integers, use this command:


java Calculator 2 + 3 

The program will display the following output:

2 + 3 = 5 
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);//from  w  w w  .j  av  a 2 s.  c  o  m
    }

    // The result of the operation
    int result = 0;

    // Determine the operator
    switch (args[1].charAt(0)) { 
      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]);
    }

    // Display result
    System.out.println(args[0] + ' ' + args[1] + ' ' + args[2]
      + " = " + result);
  }
}



PreviousNext

Related