-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);
  }
}
3
  • Java != JavaScript ;) Commented Sep 23, 2017 at 20:10
  • 1
    How are you calling main? Commented Sep 23, 2017 at 20:14
  • 1
    I suggest adding if (args.length != 2) throw new IllegalArgumentException("Expected 2 arguments, but got: " + Arrays.toString(args)) to the start of your main-method. This won't fix your problem, but will give you a better error message ;-). Commented Sep 23, 2017 at 20:17

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

5 Comments

You don't typically call main directly. It's passed at the command line
@cricket_007 I know, I was just trying to reinforce the point and was adding the command line example at that moment.
But if I do that, then I get more errors?
@K.Lujan Ok, then there are other issues with your code that need to be worked out. Take them one at a time.
@cricket_007 Thanks. I'm not a Java guy (I do C#), so I knew what the problem was, but a little rusty on the syntax.
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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.