我刚刚开始使用java,但我不太清楚错误。我认为它与我的字符串数组有关。当我运行它时,在第一次输入后,我收到错误消息:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
at CurveBreaker.main(CurveBreaker.java:13)
非常感谢任何帮助。
import java.util.Scanner;
public class CurveBreaker {
public static void main(String[]args){
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of students.");
int i = input.nextInt();
int[] StudentGrades = new int[i];
String[] Students = new String[i];
System.out.println("Enter the name of the student.");
Students [i] = input.next();
System.out.println("Enter the student's score.");
StudentGrades[i] = input.nextInt();
String Best = Students [i];
int BestNumb = StudentGrades [i];
i--;
for(i=i; i>0;i--){
System.out.println("Enter the name of the student.");
Students [i] = input.next();
System.out.println("Enter the student's score.");
StudentGrades[i] = input.nextInt();
if(StudentGrades[i] > BestNumb){
BestNumb = StudentGrades[i];
Best = Students [i];
}
}
System.out.println("The highest score was " + BestNumb + " which was achieved by " + Best);
}
}
答案 0 :(得分:1)
Java数组具有从0
到i-1
的索引。您正尝试将1
用于i
答案 1 :(得分:1)
因此,您提示用户输入元素数量......
System.out.println("Enter the number of students.");
int i = input.nextInt();
int[] StudentGrades = new int[i];
String[] Students = new String[i];
好的,那很酷,但是你呢......
System.out.println("Enter the name of the student.");
Students[i] = input.toString();
现在,这有两个问题,一个,input.toString()
不会要求用户输入,它只是分配toString
的结果到元素i
两个,i
仍然等于用户输入的值。例如,如果他们输入5
,则您尝试为元素5
分配一个值,该值不存在,因为Java数组基于0
(0-4
})
更好的解决方案可能是做一些像......
System.out.println("Enter the number of students.");
int i = input.nextInt();
input.nextLine(); // This is important, it clears the carriage return from the buffer
int[] StudentGrades = new int[i];
String[] Students = new String[i];
for (int index = 0; index < i; index++) {
System.out.println("Enter the name of the student.");
Students[i] = input.nextLine();
System.out.println("Enter the student's score.");
StudentGrades[i] = input.nextInt();
input.nextLine();
// calculate stuff here...
}
但是,你似乎想要以相反的顺序输入它们,好吧,使用像......这样的东西。
for (int index = i - 1; index >= 0; index--) {
,而不是...
您可能还想查看The Arrays tutorial