java - 从文本文件创建二维数组并求平均值
问题描述
我正在尝试从文本文件中的数字创建一个二维数组,可以打印并找到每列的平均值。注意:我在“int rows”和“int columns”上收到错误消息“类型不匹配:无法从 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() 返回一个字符串,而不是一个 int。您可以尝试类似int rows = fileScan.nextInt()
或int rows = Integer.parseInt(fileScan.nextLine());
推荐阅读
- elisp - 两者 (funcall (lambda 和 (lambda 工作
- c++ - 蒂姆排序给出了不是 2 次幂的元素数量的错误
- ruby-on-rails - 未定义方法的 redmine 插件 500 错误
- google-apps-script - 如何在对象未定义时返回属性
- python-3.x - 如何在 fastai 中显示使用 open_image 函数打开的图像?
- cordova - ajax 调用不适用于 phonegap 构建(cli 9)和 android SdkVersion 28
- ios - 如何在快速注册时检查用户是否已经注册
- json - Uncaught (in promise) SyntaxError: Unexpected end of JSON input at AddAutor.js:78
- android - 如何使用 LetterAdapter 在 Android 中制作 CircleLayout
- java - graphql spqr 页面映射异常