在下面的代码中,我需要读取五个学生姓名的列表以及每个学生五个测验的分数,这会将姓名加载到 String 类型的 ArrayList 中,并将测验分数加载到 Integer 类型的 ArrayList 中。我已经通过两个不同的 ArrayList 分解了这个问题,我希望将它们结合起来,但不确定。
以下代码读取五个学生姓名并将这些姓名加载到 String 类型的 ArrayList 中
import java.util.ArrayList;
public class QuizAveragee
{
public static void main( String[] args ) {
final int NAMELIMIT = 5 ;
final int QUIZLIMIT = 5 ;
ArrayList<String> sNames = new ArrayList<String>();
ArrayList<String> sFamily = new ArrayList<String>();
Scanner in = new Scanner(System.in);
// Load the five names of the students in the arraylist
for(int i = 1; i<=NAMELIMIT; i++)
{
String[] input = in.nextLine().split("\\s+");
sNames.add(input[0]);
sFamily.add(input[1]);
}
for(int i=0; i<NAMELIMIT; i++)
{
System.out.println("Name: " + sNames.get(i) + " " + sFamily.get(i));
}
System.out.println();
}
}
输入以下内容:
Sally Mae 90 80 45 60 75
Charlotte Tea 60 75 80 90 70
Oliver Cats 55 65 76 90 80
Milo Peet 90 95 85 75 80
Gavin Brown 45 65 75 55 80
它生成:
Name: Sally Mae
Name: Charlotte Tea
Name: Oliver Cats
Name: Milo Peet
Name: Gavin Brown
然后,我需要编写程序的一部分,为每个学生读取五个测验,并将测验标记加载到整数类型的 ArrayList 中。这是我为这部分生成的。
import java.util.ArrayList;
import java.util.Scanner;
public class heya
{
public static final int QUIZLIMIT = 5;
public static Scanner readQuiz;
public static void main(String[] args)
{
readQuiz = new Scanner(System.in);
while (readQuiz.hasNextLine()) {
ArrayList<Integer> quizMarks = readArrayList(readQuiz.nextLine());
computerAverage(quizMarks);
}
}
// Load quiz marks
public static ArrayList<Integer> readArrayList(String input)
{
ArrayList<Integer> quiz = new ArrayList<Integer>();
Scanner readQuiz = new Scanner(input);
int i = 1;
while (i <= QUIZLIMIT)
{
if (readQuiz.hasNextInt()) {
quiz.add(readQuiz.nextInt());
i++;
}
else {
readQuiz.next(); // Toss the next read token
}
}
return quiz;
}
// Compute the average of quiz marks
public static void computerAverage(ArrayList<Integer>quiz)
{
int total = 0 ;
for(Integer value : quiz)
{
total = total + value;
}
System.out.println("Quiz Avg: "+ (total/QUIZLIMIT));
}
}
给出输出:
Quiz Avg: 70
Quiz Avg: 75
Quiz Avg: 73
Quiz Avg: 85
Quiz Avg: 64
但是,我需要结合这些程序,但我不太确定该怎么做。给定的输入:
Sally Mae 90 80 45 60 75
Charlotte Tea 60 75 80 90 70
Oliver Cats 55 65 76 90 80
Milo Peet 90 95 85 75 80
Gavin Brown 45 65 75 55 80
应该给出:
Name: Sally Mae Quiz Avg: 70
Name: Charlotte Tea Quiz Avg: 75
Name: Oliver Cats Quiz Avg: 73
Name: Milo Peet Quiz Avg: 85
Name: Gavin Brown Quiz Avg: 64