java - 如何在 Java 中显示通过 do while 循环输入的输入?
问题描述
我正在开发一个程序,该程序会提示用户输入不定数量的学生姓名和数字等级。当用户输入 -1 时,程序应该停止提示用户输入。一旦发生这种情况,将显示一个成绩报告,显示每个学生的成绩、最低分、最高分和平均分。
这是它应该是什么样子的示例:
Enter the student's name or [-1] to quit: Victoria T.
Enter the student's grade or [-1] to quit: 88
Enter the student's name or [-1] to quit: Jared S.
Enter the student's grade or [-1] to quit: 93
Enter the student's name or [-1] to quit: Jaheem
Enter the student's grade or [-1] to quit: 75
Enter the student's name or [-1] to quit: -1
Class Grading Report
Victoria T.: B
Jared S.: A
Jaheem: C
Minimum: 75.0
Maximum: 93.0
Average: 64.0
到目前为止,我已经想出了如何通过 do-while 循环收集输入,但现在我正试图弄清楚如何打印出我输入的所有输入。我知道还有其他因素,例如计算最大和最小数字以及将数字等级转换为字母等级,但我只想弄清楚如何打印出我输入的输入。
到目前为止,这是我的代码:
import java.util.*;
public class CreateGradeReport {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String studentName = "";
int studentGrade = 0;
do {
System.out.print("\nEnter the student's name or [-1] to quit: ");
studentName = input.nextLine();
if (studentName.equals("-1")){
break;
}
System.out.print("\nEnter the student's grade or [-1] to quit: ");
studentGrade = input.nextInt();
if(studentGrade == -1){
break;
}
String dummy = input.nextLine();
}
while(!studentName.equals("-1") && studentGrade != -1);
}
}
对此的任何帮助将不胜感激。谢谢你。
解决方案
您需要先将输入的详细信息保存在合适的数据结构中。您可以创建一个单独的班级,其中包含学生姓名和年级的字段,如下所示:
public class StudentDetails {
public String studentName;
public int studentGrade;
public StudentDetails (String studentName , int studentGrade){
this.studentName = studentName;
this.studentGrade = studentGrade;
}
}
然后您也许可以使用此对象的 ArrayList 以这种方式保存所有数据:
import java.util.*;
public class CreateGradeReport {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String studentName = "";
int studentGrade = 0;
public ArrayList<StudentDetails> studentsDetailsList= new ArrayList<>();
do {
System.out.print("\nEnter the student's name or [-1] to quit: ");
studentName = input.nextLine();
if (studentName.equals("-1")){
break;
}
System.out.print("\nEnter the student's grade or [-1] to quit: ");
studentGrade = input.nextInt();
if(studentGrade == -1){
break;
}
// Add your data by invoking the constructor of your newly created
// class above and add it to the list.
studentsDetailsList.add(new StudentDetails(studentName, studentGrade));
String dummy = input.nextLine();
}
while(!studentName.equals("-1") && studentGrade != -1);
}
// Print your data from this list
for(StudentDetails sd : studentsDetailsList){
System.out.println(sd.studentName + ", " + sd.studentGrade);
}
}
快乐编码!
推荐阅读
- c++ - Makefile:src 目录中的所有 .cpp 和 .h 文件
- ios - 找不到目标 C 桥接头文件
- java - 获取非空对象数组
- php - Laravel js 错误 GET http://localhost:8000/admin/product/js/jquery-3.2.1.min.js 404(未找到)
- php - 如何设置我的邮件函数 php 的标题以接受 html 格式的用户输入信息和附件
- c# - 如何仅在使用 SQL 服务器的数据库填充的 datagridview 中显示日期?
- android - 检查一个值是否为空
- mysql - 带有输入和输出 SQL 的存储过程
- caching - Wildfly infinispan Web 缓存容器有什么用?
- grafana - 循环数据到 grafana