首页 > 解决方案 > 如何正确地将变量添加到数组中?

问题描述

我正在尝试将一个变量分配给一个数组,但我不断收到 ArrayIndexOutOfBounds 错误,我很困惑为什么它不起作用。

问题:编写一个程序,读取 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)

标签: javaarraysdebuggingerror-handling

解决方案


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.

推荐阅读