-2

I wrote this code for a simple calculator and I get this error! Someone help me please!

public class Calculator { 

  public static void main (String[] args) {

    int num1 = Integer.parseInt(args[0]);
    int num2 = Integer.parseInt(args[1]);
    int sum = num1 + num2;
    int sub = num1 - num2;  
    int prod = num1 * num2;
    int quot = num1 / num2;
    int rem = num1 % num2;

    // print the other variables, sub, prod, quot, rem;     
    System.out.println(num1 + " + " + num2 + " = " + sum);      
    System.out.println(num1 + " - " + num2 + " = " + sub);      
    System.out.println(num1 + " * " + num2 + " = " + prod);     
    System.out.println(num1 + " / " + num2 + " = " + quot);     
    System.out.println(num1 + " % " + num2 + " = " + rem);
  }
}
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
K. Lujan
  • 1
  • 3

2 Answers2

1

You need to make sure that when the application is started, it is passed two strings that can be parsed as numbers because your code assumes that arguments will have an element at positions 0 and 1. If you don't pass two arguments, then you will get your error.

For example, if calling main from within the program:

Calculator.main(new String[] {"10","20"});

Or, if calling Calculator.class from the command line:

java Calculator 10 20
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Scott Marcus
  • 64,069
  • 6
  • 49
  • 71
0

As the exception indicates, your program encountered an Array out of bounds exception when it tried to access an array within index of 0. The only place in your code above where in Array with an index of 0 is being accessed is at the following line

int num1 = Integer.parseInt(args[0]);

So in other words, your program couldn't find 0th index of the args array which means you haven't passed any arguments to your program. Looks like your program two arguments in fact. Run your program the following way if you are using command line

java Calculator 100 200

VHS
  • 9,534
  • 3
  • 19
  • 43