gpt4 book ai didi

java - 如何在数组中显示成绩?

转载 作者:行者123 更新时间:2023-11-29 03:07:25 25 4
gpt4 key购买 nike

教授的示例输出: Sample output given scores.txt file

到目前为止我的代码:

import java.util.*;
import java.io.*;
import java.text. DecimalFormat;
public class HW10 {
public static void main(String[] args) throws IOException {

System.out.println("Which file would you like to read?");

Scanner keyboard = new Scanner(System.in);
String name = keyboard.next();
Scanner reader = new Scanner(new File(name));

double numbers[][] = new double[reader.nextInt()+1][reader.nextInt()+1]; //+1 for averages

//loop over all the rows
for (int i=0; i<numbers.length; i++) {
//loop over all the columns in row i
for (int j=0; j<numbers[i].length; j++) {
//this code will execute on each and every cell row i, column j
numbers[i][j] = reader.nextDouble();
}
double sum = 0;
double average = (sum/(numbers.length));
}
//loop over all the rows
for (int i = 0; i<numbers.length-1; i++) {
System.out.println("Assignment #: ");
System.out.println("array 1, 2, 3, 4, 5, 6, Avg");
System.out.println("Student 1: ");
System.out.println("Student 2: ");
System.out.println("Student 3: ");
System.out.println("Student 4: ");
System.out.println("Student 5: ");
System.out.println("Average: ");

for (int j=0; j<numbers[i].length-1; j++) { //loop over all the columns in row i
System.out.print(numbers[i][j] + " "); //print out the cell value and then a space
}
//System.out.println("The overall class average is " + (totalResults/(numbers.length))); //the class average
DecimalFormat numPattern = new DecimalFormat("##.#");
}
//overall average code here
}
}

为了正确显示所有内容,需要显示数组以使标题和打印行都有意义。我通过将一些占位符放在我不了解如何显示数据的地方来做到这一点。

虽然上面的代码可以编译,但当输入 scores.txt 文件作为名称时,它会给我一个异常错误——工作目录包含该文件,所以我不确定为什么它没有在程序中移动过去, 要么。

我认为如果我能克服这个障碍,我将能够很好地显示数组,但我寻求 Stack 关于我的代码在语法上的外观的建议。有任何改进的见解吗?

最佳答案

要格式化输出,请使用 String.format()。

System.out.println(String.format("%4d", 5));// for int
System.out.println(String.format("%-20s= %s" , "label", "content" ));//for string

在哪里

%s is a placeholder for you string.

The '-' makes the result left-justified.

20 is the width of the first string

see link

另一个问题是关于文件打开。

仅提供文件名无济于事。尝试给出整个路径。

使用 System.getProperty("user.dir"); 获取路径

String name = keyboard.next();
String path = System.getProperty("user.dir");
Scanner reader = new Scanner(new File(path + " \\ " + name));

关于java - 如何在数组中显示成绩?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31425053/

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