我正试图从文本文件中的数字创建一个2D数组,该数组可以打印出来,并可以找到每列的平均值。注意:在"int行"one_answers"int列"上,我收到一个错误,说"类型不匹配:无法从java.lang.String转换为int"。如有任何反馈,我们将不胜感激。
示例文本文件:
3
4
6 4 2 12
3 5 6 0
11 0 3 0
输出示例:
分数数组:
[6,4,2,12]
[3,5,6,0]
[11,0,3,0]
每次作业平均得分:
作业#1平均值:6.66666666666
作业#2平均:9.0
作业#3平均值:3.66666666666
作业#4平均:4.0
import java.util.Scanner;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Arrays;
public class Scores {
public static void main(String[] args) throws FileNotFoundException {
Scanner keyboard = new Scanner(System.in);
System.out.println("What is the name of the file containing the scores?");
String fileName = keyboard.nextLine();
Scanner fileScan = new Scanner(new File(fileName));
//TODO: read in the values for the number of students and number of assignments using the Scanner on the file
//TODO: create a 2-D to store all the scores and read them all in using the Scanner on the file
int rows = fileScan.nextLine();
int columns = fileScan.nextLine();
int [][] myArray = new int[rows][columns];
while(fileScan.hasNextLine()) {
for (int i=0; i<myArray.length; i++) {
String[] line = fileScan.nextLine().trim().split(" ");
for (int j=0; j<line.length; j++) {
myArray[i][j] = Integer.parseInt(line[j]);
}
}
}
System.out.println("Array of scores:");
//TODO: print the entire array, row by row, using Arrays.toString()
System.out.println(Arrays.deepToString(myArray));
System.out.println("Average score of each assignment:");
//TODO: compute and print the average on each assignment
double total=0;
int totallength,assignment;
for(int i=0;i<myArray.length;i++) {
for(int j=0;j<myArray[i].length;j++) {
total+=myArray[i][j];
totallength++;
System.out.println("Assignment #" + assignment++ + " Average: " + (total/totallength));
}
}
fileScan.close();
}
}
Scanner.nextLine((返回一个String,而不是int。您可以尝试类似int rows = fileScan.nextInt()
或int rows = Integer.parseInt(fileScan.nextLine());
的方法
您的问题是从文件中读取rows
和columns
时它们是字符串。您需要将它们转换为整数,然后才能将它们用作数组索引。所以这样做吧:
int rows = Integer.parseInt(fileScan.nextLine());
int columns = Integer.parseInt(fileScan.nextLine());