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");
}
}
}
a < nums.length- save yourself many key strokes over your lifetime.