gpt4 book ai didi

java - 当我们在 for 循环中重复询问时,如何存储输入

转载 作者:行者123 更新时间:2023-12-01 10:40:08 25 4
gpt4 key购买 nike

public class Exercise_09 {

public static void main(String[] args) {

Scanner input = new Scanner(System.in);
System.out.print("Enter the number of student: ");
int studentCount = input.nextInt();
input.nextLine();

String topSName = null;
double topSScore = 0;
String secondSName = null;
double secondSScore = 0;

for (int i = 0; i < studentCount; i++) {
System.out.print("Enter name for student #" + (i + 1) + ": ");
String s = input.next();

System.out.print("Enter score for student #" + (i + 1) + ": ");
double score = input.nextDouble();

if (score > topSScore) {
if (topSName != null) {
secondSName = topSName;
secondSScore = topSScore;
}
topSName = s;
topSScore = score;
} else if (score > secondSScore) {
secondSName = s;
secondSScore = score;
}

}
System.out.println("Top student " + topSName + "'s score is " + topSScore);
System.out.println("Second top student " + secondSName + "'s score is " + secondSScore);
}

}

好的,我得到了这段代码,它的作用是询问学生人数、他们的姓名和分数,并显示最高分和第二高分。

现在我的问题是,当我重复询问学生姓名和分数时,输入如何保留所有分数和姓名的记录以及如何调用它? if 语句逻辑到底在做什么?我不明白那部分。

最佳答案

您可以使用数组列表来存储姓名和分数。

将数据存储到 arraylist 后,您可以显示 arraylist 中的数据。

这里http://www.careerbless.com/samplecodes/java/beginners/collections_ds/inertandretrieveArrayList.php您可以获取如何从数组列表插入和检索值的示例。

关于java - 当我们在 for 循环中重复询问时,如何存储输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34469121/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com