我很难理解如何制作我的节目。程序看起来应该是这样的:
Number of students: 3
Number of exams : 3
Enter student's data (first name follow by exam scores):
Joe 85 88 93
Mike 90 100 97
Bill 50 68 73
Name E1 E2 E3 Grade
Joe 85 88 93 88.666666666667
Mike 90 100 97 95.666666666667
Bill 50 68 73 63.666666666664
我正在介绍Java课程,所以我本周刚刚学习了Arrays。
到目前为止,我的代码看起来像这样。
import java.util.Scanner;
public class GradeCalcWithArrays {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int students = 0;
int exams = 0;
System.out.println("Number of students: ");
students = s.nextInt();
String names[] = new String[students];
System.out.println("Number of exams: ");
exams = s.nextInt();
int scores[][] = new int[students][exams];
for (int i, j = 0;;) {
System.out
.println("Enter student's data (first name followed by exams scores):");
String studentnames = s.nextLine();
studentnames = names[3];
int e1 = s.nextInt();
e1 = scores[0][0];
int e2 = s.nextInt();
e2 = scores[0][2];
int e3 = s.nextInt();
e3 = scores[0][3];
}
}
}
我很乐意为这些阵列提供一些帮助。我想我正在尝试输入的方式。但是一旦我进入我的老师所说的我需要使用的双阵列,我就不知所措,我不知道如何输入数组。非常感谢任何帮助。
到目前为止我的程序输出是:
Number of students: 3
Number of exams: 3
Enter student's data (first name follow by exam scores):
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3
at GradeCalcWithArrays.main(GradeCalcWithArrays.java:25)
我正在使用Eclipse,如果这也是提供帮助的因素。
答案 0 :(得分:0)
数组索引从0开始。由于name
是一个String
数组,可以容纳3个元素,因此有效索引是0-2。您尝试在String
中存储studentnames
(name[3]
)这是一个无效的位置。因此,您会收到ArrayOutOfBounds
个异常。
所以你的代码应该是:
import java.util.Scanner;
public class GradeCalcWithArrays {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
int students = 0;
int exams = 0;
System.out.println("Number of students: ");
students = s.nextInt();
String names[] = new String[students];
System.out.println("Number of exams: ");
exams = s.nextInt();
int scores[][] = new int[student][exams];
for (int i = 0;i<students; i++) {
System.out.println("Enter student "+ i+1 +" data (first name followed by exams scores):");
names[i] = s.nextLine();
for(int j=0;j<exams;j++)
{
scores[i][j] = s.nextInt();
}
}
//Rest of your code to print the table goes here
}
}