Я пытаюсь присвоить переменную массиву, но продолжаю получать ошибку 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)