gpt4 book ai didi

java - 从文本文件创建二维数组并查找平均值

转载 作者:行者123 更新时间:2023-12-02 09:19:24 25 4
gpt4 key购买 nike

我正在尝试从文本文件中的数字创建一个二维数组,可以打印该数组并找到每列的平均值。注意:我收到一条错误消息,指出“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 rows = fileScan.nextInt()int rows = Integer.parseInt(fileScan.nextLine());

关于java - 从文本文件创建二维数组并查找平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58792692/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com