问题来自“嵌套的循环”一章,因此我假设我应该为此使用嵌套的循环。
在入学考试中,学生回答了英语,数学和科学论文。编写一个程序来计算和显示所有学生获得的平均成绩。以每个学生在所有三个科目中出现的学生人数和分数以及姓名作为输入。
这是我的代码:
import java.io.*;
class average
{
public static void main(String args[]) throws IOException
{
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
int i,j,m,s,e,sum;
String name;
double a;
System.out.println("Enter number of students that appeared");
int n = Integer.parseInt(in.readLine());
for(i=1;i<=n;i++)
{
System.out.println("Enter name");
name = in.readLine();
System.out.println("Enter marks obtained in English");
e = Integer.parseInt(in.readLine());
System.out.println("Enter marks obtained in Maths");
m = Integer.parseInt(in.readLine());
System.out.println("Enter marks obtained in Science");
s = Integer.parseInt(in.readLine());
sum = e + m + s;
a = sum/3.0;
System.out.println("Average Marks = "+a);
}
}
}
那么我该如何正确使用Nested For Loop?我误解了这个问题吗?如果是这样,那我该怎么办?
答案 0 :(得分:0)
我认为您不应在代码段中使用嵌套循环。您应该将其分为两部分:接收学生的数据和推算学生的数据。
首先,定义一个代表学生分数的班级:
public final class StudentScore {
private final String name;
private final int scoreEnglish;
private final int scoreMaths;
private final int scoreScience;
// TODO a put this parameter hered, but probably it's is better to calculate id every time when required
private final double avg;
public StudentScore(String name, int scoreEnglish, int scoreMaths, int scoreScience) {
this.name = name;
this.scoreEnglish = scoreEnglish;
this.scoreMaths = scoreMaths;
this.scoreScience = scoreScience;
avg = (scoreEnglish + scoreEnglish + scoreEnglish) / 3.;
}
// getters
}
第二,定义一种方法,该方法使用Scanner
(与使用控制台的InputStreamReadr
比较有用)来接收大量学生和学生数据:
private static List<StudentScore> getStudentsScore() {
try (Scanner scan = new Scanner(System.in)) {
System.out.print("Enter number of students that appeared: ");
int total = scan.nextInt();
List<StudentScore> studentScores = new ArrayList<>(total);
for (int i = 0; i < total; i++) {
System.out.print("Enter name: ");
String name = scan.nextLine();
System.out.print("Enter marks obtained in English: ");
int scoreEnglish = scan.nextInt();
System.out.print("Enter marks obtained in Maths: ");
int scoreMaths = scan.nextInt();
System.out.println("Enter marks obtained in Science");
int scoreScience = scan.nextInt();
studentScores.add(new StudentScore(name, scoreEnglish, scoreMaths, scoreScience));
}
return studentScores;
}
}
第三,您要做的只是接收学生的数据列表并预选所需的参数:
List<StudentScore> studentScores = getStudentsScore();
studentScores.forEach(studentScore -> System.out.format("Average Marks for student '%s' is '%.2f'\n", studentScore.getName(), studentScore.getAvg()));
PS
目前尚不清楚您应该计算出多少完美的平均分数,但是当您收到List<StudentScore> studentScores
时,就可以计算出所需的全部分数。