[英]How do i work with two dimensional arrays
I constructed (poorly) a two dimensional array to hold student names and the grades. 我构造了(很差)一个二维数组来容纳学生的姓名和成绩。 It does prompt me for the names of students equal to the amount that i want, but it dosn't for grades.
它的确提示我输入的学生姓名等于我想要的数量,但不要求成绩。 Also it states that i have a index out of bounds, which i dont see how that happened.
它还指出我有一个超出范围的索引,我不知道那是怎么发生的。
private void studentArray() {
int rows = 0;
int col = 0;
Scanner input = new Scanner(System.in);
System.out.println("How many students do you have?");
rows = input.nextInt();
System.out.println("How many tests would you like to record?");
col = input.nextInt();
String [][] schoolArray = new String[rows][col];
for (int row = 0; row < rows; row++ ){
System.out.println("Please enter student name.");
schoolArray[row][0] = input.next();
for(int cols = 1; cols < col; cols++){
System.out.println("Please enter grades.");
schoolArray[cols][0] = input.next();
}//end of col for loop
}//end of row for loop
printSchool (schoolArray, rows, col);
}//end of studentArray
private void printSchool(String[][]schoolArray, int rows, int col){
for ( int row = 0; row < schoolArray.length; row ++) {
System.out.print(schoolArray[rows][col + 1] + "\t");
}
}
我认为您是误将其写成school[cols][0]
,应该是在col for loop里面是school[row][cols]
First use- 首次使用-
schoolArray[row][cols] = input.next();
instead of 代替
schoolArray[cols][0] = input.next();
and also change the printSchool method- 并更改printSchool方法-
private void printSchool(String[][]schoolArray, int rows, int col){
for ( int row = 0; row < rows; row ++) {
System.out.print("\n");
for(int cols= 0; cols < col ;cols++){
System.out.print(schoolArray[row][cols] + "\t");
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.