我正在尝试打印输入用户输入的号码,但是我收到了错误消息。这是我的代码:
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
int size=0,score=0;
int [] a=new int[size];
int len=a.length;
do
{
System.out.print("Please enter a number between 1 to 5: ");
size=input.nextInt();
}
while ((size<1) || (size>5));
for (int i=1;i<=size;i++)
{
do
{
System.out.print("Enter your "+i+" score (1-100):");
score=input.nextInt();
}
while((score<1) || (score>100));
}
for (int i=1;i<=size;i++)
System.out.println(a[i]+ " ");
}
}
这是我的输出和错误: 请输入1到5:2之间的数字 输入你的1分(1-100):54 输入你的2分(1-100):64 线程“main”中的异常java.lang.ArrayIndexOutOfBoundsException:1 在Week08.BigArray2.main(BigArray2.java:27)
答案 0 :(得分:1)
您的代码中有四个错误
扫描仪未关闭
Scanner input = new Scanner(System.in);
int size = 0, score = 0;
do {
System.out.print("Please enter a number between 1 to 5: ");
size = input.nextInt();
} while ((size < 1) || (size > 5));
int[] a = new int[size]; //1
for (int i = 0; i < size; i++) {
do {
System.out.print("Enter your " + (i + 1) + " score (1-100):");
score = input.nextInt();
a[i] = score; //2
} while ((score < 1) || (score > 100));
}
for (int i = 0; i < size; i++) //3
System.out.print(a[i] + " ");
input.close(); //4
输出
Please enter a number between 1 to 5: 4
Enter your 1 score (1-100):99
Enter your 2 score (1-100):98
Enter your 3 score (1-100):97
Enter your 4 score (1-100):96
99 98 97 96
答案 1 :(得分:0)
您的代码几乎没有问题:
这是修改后的工作程序:
import java.util.Scanner;
public class ArrayPrint {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int size = 0, score = 0;
int[] a;
do {
System.out.print("Please enter a number between 1 to 5: ");
size = input.nextInt();
} while ((size < 1) || (size > 5));
//Allocating space to array
a = new int[size];
int len = a.length;
for (int i = 0; i <size; i++) {
do {
System.out.print("Enter your " + i + " score (1-100):");
score = input.nextInt();
a[i] = score;
} while ((score < 1) || (score > 100));
}
for (int i = 0; i <size; i++)
System.out.println(a[i] + " ");
}
}
<强>输出强>
Please enter a number between 1 to 5: 2
Enter your 0 score (1-100):22
Enter your 1 score (1-100):11
22
11
答案 2 :(得分:0)
请查看您的第4行代码int [] a=new int[size];
,此时大小= 0并且您已初始化整数数组&#34; a&#34;大小为0,但你试图迭代数组&#34; a&#34;最后使用代码for (int i=1;i<=size;i++)
System.out.println(a[i]+ " ");
}
导致数组索引超出绑定异常。
首先执行while循环后移动下面的代码行 - :
int[] a = new int[size];
int len = a.length;
现在更正你的最后一个for循环 - :
for (int i = 0; i < size; i++)
System.out.println(a[i] + " ");
}
数组索引从 0 开始,以 size-1 结束。