该程序的目标是询问用户数组的大小和数量,并选择是否添加或减去数组的内容。错误来自我查找的内容是我的程序正在尝试访问我的数组但那里什么都没有?还在学习数组。
我的代码:
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");
}
}
}