教授的样本输出:
到目前为止我的代码:
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关于我的代码在语法上看起来如何的建议。有任何改进的见解吗?
答案 0 :(得分:2)
格式化输出使用String.format().
System.out.println(String.format("%4d", 5));// for int
System.out.println(String.format("%-20s= %s" , "label", "content" ));//for string
哪里
%s是您字符串的占位符。
' - '使结果左对齐。
20是第一个字符串的宽度
另一个问题是文件打开。
仅提供文件名无济于事。尝试给出整条路径。
使用System.getProperty("user.dir");
String name = keyboard.next();
String path = System.getProperty("user.dir");
Scanner reader = new Scanner(new File(path + " \\ " + name));