0

该程序的目标是询问用户数组的大小和数量,并选择是否添加或减去数组的内容。错误来自我查找的内容是我的程序正在尝试访问我的数组但那里什么都没有?还在学习数组。

我的代码:

import java.util.Scanner;
public class ArrayCalculator {
  public static void main(String[] args)
  {
          Scanner scan = new Scanner(System.in);
          System.out.println("Welcome to the Array Calculator Program!");
          System.out.println("");
          System.out.println("Enter the size of the array (-1 to quit): ");
          int size = scan.nextInt();
           if ( size == -1)
           {
                   System.out.println("Program stopped");
                   System.exit(-1);
           }

           System.out.println("Enter " + size + " integers:");

           double[] nums;
           nums = new double[size];

           for (int i=0; i<= nums.length-1; ++i)
           {
                   nums[i] = scan.nextDouble();
           }


           System.out.println("Multiply or add (*, +) ? :");
           char sign = scan.next().charAt(0);


           switch ( sign )
            {
            case '*':
                double total= nums[0];
                for (int a = 1; a <=nums.length; ++a)
                {

                 total = total * nums[a];   
                }
                System.out.println("The product of the numbers is " + total);
                break;
            case '+':
                double total1= nums[0];
                for (int a = 1; a <=nums.length; ++a)
                {

                 total1 = total1 + nums[a]; 
                }
                System.out.println("The sum of the numbers is " + total1);
                break;
            default:
                System.out.println("Input is invaild");
        }
  }

}

4

1 回答 1

2

就在这里:a <=nums.length。那应该是a <=nums.length - 1or a < nums.length,但是您已经知道了,正如我看到您在这里所做的那样:i<= nums.length-1;.

在 Java 中,索引是从 开始的0,所以如果你尝试这样做,nums[nums.length]你会得到Array Index out of Bounds异常,因为最后一个元素是nums[nums.length - 1].

于 2013-09-12T22:17:31.537 回答