ArrayIndexOutOfBounds与String数组?

时间:2015-09-16 00:35:38

标签: java arrays

我正在尝试创建一个捕获NumberFormatException的简单计算器,但由于某种原因,我在运行程序时遇到错误。 这是错误:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
    at MyNumberFormatException.main(MyNumberFormatException.java:14)

这是我的代码:

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");
      }

   }
}

更好的选择是使用ArrayList吗?如果是这样,我将如何进行切换语句,其中包含.charAt(0);

1 个答案:

答案 0 :(得分:0)

如果你使用了一个arraylist并且没有为它指定一个限制性的长度,那就更好了。