java - 如何正确将变量添加到数组?

标签 java arrays debugging error-handling

我正在尝试将变量分配给数组,但是我不断收到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/

相关文章:

java - JSoup 返回不完整的 HTML 文档

c++ - 如何在 VC++ 中创建可变大小的字符数组

python - numpy 记录数组与时间?

javascript - 如何从JS中的数组中删除特定字符?

c++ - Netbeans "Resolve missing debugger command"C++

objective-c - 数组在 Xcode 4 调试器中显示为空,即使它们不是

java - 通过JSP连接MySql时出错

Java mysql 如果表存在

java - 从客户端调用时,jax-ws DataHandler getName() 为空

java - java.lang.IndexOutOfBoundsException 事件上的断点