我正在尝试将变量分配给数组,但是我不断收到ArrayIndexOutOfBounds错误,但我对为什么它不起作用感到困惑。
问题:
编写一个程序,该程序读取任意数量的整数(范围为0到50,包括0和50),并计算每次输入多少次。用超出范围的值指示输入的结尾。处理完所有输入后,打印一次或多次输入的所有值(以及出现的次数)。
import java.util.Scanner;
public class IntCounter {
public static void main (String[]args) {
//variables
int i = 0;
final int MaxValue = 51;
int userInput[]=new int[i]; //Initializing array to store user unput
Scanner scan = new Scanner(System.in); //Initializing scanner
for(i=0; i<MaxValue; i++) {
System.out.println("please enter a number" + "between 0 and 50, or greater then 50 to finish"");
int u = scan.nextInt();
if (u<MaxValue) {
userInput[i]=u; //THIS IS WHERE THE ERROR IS
}
}
//outputs array values after typing a value out of range
for(int o=0; o<=i; o++,i++) {
System.out.println("Your values are:" + userInput[i]);
}
}}
OUTPUT:
please enter a number
4
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at IntCounter.main(IntCounter.java:21)
最佳答案
int i = 0;
int userInput[]=new int[i]; // here you are creating an array of length 0. so you can not assign any value in it.
int userInput[]=new int[MaxValue];// I think you mean this while creating array.
关于java - 如何正确将变量添加到数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58123076/