java - 如何正确地将变量添加到数组中?
问题描述
我正在尝试将一个变量分配给一个数组,但我不断收到 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)
解决方案
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.
推荐阅读
- reactjs - 为什么我无法创建新的 React 应用程序?
- f# - 尝试在 F# 中比较列表中的所有元素
- javascript - OnClick -> 使用 QUnit 检查 ajax 更新
- hibernate - session.delete() 和 session.remove() 有什么区别?
- python - Python:在具有特定键的另一个字典的字典列表中查找字典
- reactjs - React - typescript TypeScript 错误:此表达式不可调用
- tensorflow - Keras 功能 API 多输入形状错误
- css - 如何在 Chrome 中停止默认的褪色背景图像效果?
- java - 查询期间休眠警告 - 使用 Pageable 进行左连接获取
- javascript - 如何通过全局模式从路径中提取目录?