I am trying to create a simple calculator that catches a NumberFormatException, but for some reason I am getting an error when I run my program. This is the error:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at MyNumberFormatException.main(MyNumberFormatException.java:14)
This is my code:
import java.util.*;
public class MyNumberFormatException
{
public static void main(String [] args)
{
//Create new array
String [] operations = new String[2];
//Create Scanner object
Scanner input = new Scanner(System.in);
//Get first integer from user
System.out.println("Enter your first integer: ");
operations[0] = input.next();
//Get operator from user
System.out.println("Enter your operator: ");
operations[1] = input.next();
//Get second integer from user
System.out.println("Enter your second integer: ");
operations[2] = input.next();
//Check to see if length of array is not equal to 3
if (operations.length != 3)
{
System.out.println("Usage: java Calculator operand1 operator operand2");
System.exit(0);
}
//Invoke method with array
run(operations);
}
public static void run(String [] operations)
{
//The result of the operation
int result = 0;
try {
//Determine the operator
switch(operations[1].charAt(0))
{
case '+': result = Integer.parseInt(operations[0]) + Integer.parseInt(operations[2]);
break;
case '-': result = Integer.parseInt(operations[0]) - Integer.parseInt(operations[2]);
break;
case '*': result = Integer.parseInt(operations[0]) * Integer.parseInt(operations[2]);
break;
case '/': result = Integer.parseInt(operations[0]) / Integer.parseInt(operations[2]);
}
//If no exception is thrown, show result
System.out.println("The result of: " + operations[0] + " " + operations[1] + " = " + operations[2]);
}
//If exception is thrown, catch it and print error.
catch (NumberFormatException ex)
{
System.out.println("Error");
}
}
}
Would a better alternative be using an ArrayList? If so, how would I go about doing the switch statement where it says .charAt(0);