我从下面程序的命令行读取此文件:
Student1
5
a Activities 0.05
q Quizzes 0.10
p Projects 0.25
e Exams 0.30
f Final 0.30
**a100 a95 a100 a100 a100
q90 q80 q100 q80 q80 r90
p100 p95 p100 p85 p100
e77.5 e88
f92**
GradeBookApp.java
public class GradeBookApp {
public static void main(String[] args) throws IOException {
String fileName = "";
String name = "";
char[] categoryCodes = new char[5];
String[] categories = new String[5];
double[] categoryWeights = new double[5];
double[][] gradeTable;
if (args.length > 0) {
for (int i = 0; i < args.length; i++) {
System.out.println("Reading file \"" + args[i] + "\"."
+ "\n\tCreating GradeBook object."
+ "\n\tAdding grades to GradeBook object."
+ "\nProcessing of file complete.");
fileName = args[i];
Scanner scanFile = new Scanner(new File(fileName));
name = scanFile.nextLine();
int catCodes = Integer.parseInt(scanFile.nextLine());
for (i = 0; i < catCodes; i++) {
String[] all = scanFile.nextLine().split(" ");
if(all.length == 3 && all[0].length() == 1 && all[2].matches("(\\d+\\.\\d+)")){
categoryCodes[i] = all[0].charAt(0);
categories[i] = all[1];
categoryWeights[i] = Double.parseDouble(all[2]);
}
}
GradeBook myGB = new GradeBook (name, categoryCodes,
categories, categoryWeights);
}
}
我有另一个包含方法&#34; addGrade&#34;它接受参数&#34; newGradeIn&#34;。此参数是正在读取的文件的等级,即a100或e88。对于要添加的每个等级,我将原始2D数组替换为另外一个等级。
public boolean addGrade(String newGradeIn) {
char row = newGradeIn.charAt(0);
int grade = Integer.parseInt(newGradeIn.substring(1));
double[] oldArr = gradeTable[row];
double[] newArr = Arrays.copyOf(oldArr, oldArr.length + 1);
newArr[newArr.length - 1] = grade;
gradeTable[row] = newArr;
return row != 0;
}
我完全不知道如何做到这一点。我知道我应该使用for-each循环,但我不确定如何解决这个问题。
答案 0 :(得分:0)
由于您要使用成绩a
中的a100
来存储100
作为学生a
的成绩,您应该考虑使用Map
而不是2D数组。例如:
Map<String, double[]> gradeTable = new HashMap<>();
public void addGrade(String newGradeIn) {
String row = newGradeIn.substring(0,1); // use the 'a' as a key in the hashmap to the grades of student `a`
int grade = Integer.parseInt(newGradeIn.substring(1));
double[] oldArr = gradeTable.get(row);
if (oldArr == null) { // when you start - the hash-map is empty so we need to initialize the array
oldArr = new double[0];
}
double[] newArr = Arrays.copyOf(oldArr, oldArr.length + 1);
newArr[newArr.length - 1] = grade;
gradeTable.put(row, newArr);
}
用法很简单:
GradeBook g = new GradeBook();
g.addGrade("a100");
g.addGrade("a95");
g.addGrade("b90");
g.addGrade("b95");
System.out.println(Arrays.toString(g.gradeTable.get("a"))); // [100.0, 95.0]
System.out.println(Arrays.toString(g.gradeTable.get("b"))); // [90.0, 95.0]