[英]Creating a 2D Array from a Text File and Finding Average
我正在尝试从文本文件中的数字创建一个二维数组,可以打印并找到每列的平均值。 注意:我在“int rows”和“int columns”上收到错误消息“类型不匹配:无法从 java.lang.String 转换为 int”。 任何反馈将不胜感激。
示例文本文件:
3
4
6 4 2 12
3 5 6 0
11 0 3 0
示例 Output:
分数数组:
[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() 返回一个字符串,而不是一个 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());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.