public char[] calculateGrade(int [] scores, char [] grades){
for (int r = 0; r < scores.length; r++){
//System.out.println(scores[r] + " ");
if (scores[r] > 90)
grades[r] = 'A';
else if (scores[r] > 80)
grades[r] = 'B';
else if (scores[r] > 70)
grades[r] = 'C';
else if (scores[r] > 60)
grades[r] = 'D';
else
grades[r] = 'F';
for (int i = 0; i < grades.length; i++)
System.out.println(grades[i]);
}
return grades;
}
以上是我整个计划的一小部分,它从文件中获取分数并将其转换为字母等级。我需要将这些字母等级放入该文件中。字母等级需要与分数相对应。一次一行有26个不同的分数。我会将我的整个代码放在这里,但它确实很长。请帮帮我们!
答案 0 :(得分:3)
我建议让每种方法做一件事,做得好。不要计算成绩并打印出来。
public void printGrades(PrintStream ps, char [] grades) {
for (char grade : grades) {
ps.println(grade);
}
}
public char[] calculateGrade(int [] scores){
char [] grades = new char[scores.length];
for (int r = 0; r < scores.length; r++){
if (scores[r] > 90)
grades[r] = 'A';
else if (scores[r] > 80)
grades[r] = 'B';
else if (scores[r] > 70)
grades[r] = 'C';
else if (scores[r] > 60)
grades[r] = 'D';
else
grades[r] = 'F';
}
return grades;
}
答案 1 :(得分:1)
将您的方法更改为以下内容:
public void calculateGrade(int[] scores, char[] grades){
for (int r = 0; r < scores.length; r++) {
if (scores[r] > 90)
grades[r] = 'A';
else if (scores[r] > 80)
grades[r] = 'B';
else if (scores[r] > 70)
grades[r] = 'C';
else if (scores[r] > 60)
grades[r] = 'D';
else
grades[r] = 'F';
}
}
无需返回grades
,因为数组无论如何都是通过引用传递的。然后在您的调用方法(main
?)中,您应该将grades
写入所需的文件。
要写入文件,请参阅:http://www.exampledepot.com/egs/java.io/WriteToFile.html
类似于:
try {
PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("filename")));
for( char grade : grades )
out.println(grade);
out.close();
} catch (IOException e) { }