0

Objective of the program is to ask the user for the size and the numbers of the array and to choose whether to add or subtract the contents of the array. The error is from what I looked up is my program is trying to access my array but there is nothing there? Still learning Arrays.

My code:

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

}

1
  • a < nums.length - save yourself many key strokes over your lifetime. Commented Sep 12, 2013 at 22:20

1 Answer 1

2

Right here: a <=nums.length. That should be a <=nums.length - 1 or a < nums.length, but you already know that, as I see that you did that here: i<= nums.length-1;.

In Java, indexing is starting from 0, so if you try to do nums[nums.length] you will get Array Index out of Bounds exception, as the last element is nums[nums.length - 1].

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.