import java.util.Scanner;
public class ProgramAssignment1 {
public static void main(String[] args) {
reader();
}
public static void reader() {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the Number of Students you would like to input for");
int count = input.nextInt();
int[] scores = new int[count];
String[] name = new String[count];
for (int i = 1; i <= count;i++) {
System.out.println("Please input the students names ");
name[i] = input.nextLine();
System.out.println("What is there score?");
scores[i] = input.nextInt();
}
for (int a = 1; a <= 10; a++) {
System.out.print(name[a]);
System.out.print(" "+scores[a]);
}
System.out.println();
}
}
所以基本上我需要用户输入数组,但它一直给我同样的错误
示例运行:
Please enter the Number of Students you would like to input for
2
Please input the students names
What is there score?
5
Please input the students names
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2
at ProgramAssignment1.reader(ProgramAssignment1.java:18)
at ProgramAssignment1.main(ProgramAssignment1.java:7)
Java Result: 1
BUILD SUCCESSFUL (total time: 5 seconds)
答案 0 :(得分:2)
在Java中,数组的索引从0
到length - 1
,而不是1
到length
。数组是从0开始的。你将一个太高的循环,并且你的阵列结束了。
更改
for (int i = 1; i <= count;i++) {
到
for (int i = 0; i < count;i++) {
您需要同样更改a
for
循环(到达count
时停止,而不是10
)。
答案 1 :(得分:0)
1。您正在迭代循环到10。
for (int a = 1; a <= 10; a++)
假设计数小于10.会发生什么? ArrayIndexOutOfBoundsException
2. 更改
`for (int i = 1; i <= count;i++)`
进入
for (int i = 0; i < count;i++)
答案 2 :(得分:0)
你的问题是索引从0开始而不是1 变化:
for (int i = 1; i <= count;i++) {
System.out.println("Please input the students names ");
name[i] = input.nextLine();
System.out.println("What is there score?");
scores[i] = input.nextInt();
}
要:
for (int i = 0; i <= count;i++) {
System.out.println("Please input the students names ");
name[i] = input.nextLine();
System.out.println("What is there score?");
scores[i] = input.nextInt();
}
答案 3 :(得分:0)
数组从索引0开始。尝试迭代从0开始的布尔。
答案 4 :(得分:0)
Java中的数组与大多数编程语言Arrays
一样,使用offset
进行处理。
这意味着name[1]
指向名称数组开头之后的对象1,因为偏移量是1。
相反,数组的第一个元素是0 past that start of the array
或name[0]
,最后一个元素是the length of the array minus one past the begining of the array
或name[ name.length - 1 ]
在你的代码for (int i = 1; i <= count;i++) {
中经历了偏移1,2,3,4,5
,但是5是在数组开始之后的5,或者是5元素数组的第六个元素。
调整代码,使循环使用偏移0,1,2,3,4
,你应该好好去。
答案 5 :(得分:0)
例如,如果我有:
int[] array = {1,2,3,4,5,6,7,8,9,10}
for(int i=0; i<array.length; i++ {
System.out.println(array[i] + " ")
}
我会得到: 1 2 3 4 五 6 7 8 9 10
如果我的for循环来自i = 1; I&LT = array.length; i ++,我会得到: 2 3 4 5 6 7 8 9 10 [超出界限]