java - 如何根据长度循环以下程序
问题描述
我添加了一个大小为 3 的 for 循环,它应该扫描 3 次,但它正在扫描 4 次。对于 4 的大小,它的扫描 6 次帮助我。
public class Control {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
List<Student> studs = new ArrayList<Student>();
for (int i = 1;i < 3;i++) { //Here the for loop
System.out.println("Enter age and name :");
Student stu1 = new Student(sc.nextInt(),sc.nextLine());
System.out.println("Enter age and name :");
Student stu2 = new Student(sc.nextInt(),sc.nextLine());
studs.add(stu1);
studs.add(stu2);
Collections.sort(studs,new StudAge());
}
for(Student stud : studs) {
System.out.println(stud);
}
}
}
解决方案
import java.awt.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<Student> studs = new ArrayList<Student>();
for (int i = 1;i < 3;i++) { //Here the for loop
System.out.println("Enter age and name :");
int age = sc.nextInt();
//nextInt does not account for the enter that you press when you submit the int so you have to catch the unused enter keystroke
sc.nextLine();
String name = sc.nextLine();
Student stu1 = new Student(age, name);
age = sc.nextInt();
sc.nextLine();
name = sc.nextLine();
System.out.println("Enter age and name :");
Student stu2 = new Student(age, name);
studs.add(stu1);
studs.add(stu2);
Collections.sort(studs,new StudAge());
}
for(Student stud : studs) {
System.out.println(stud);
}
}
}
nextInt 不考虑您在提交 int 时按下的 enter,因此您必须捕获未使用的 enter 击键
推荐阅读
- c# - SQL 如何替换一个值
- python - 使用 python 和请求,如何进行正确的 POST 调用以及在哪里找到标头?
- android - FirebaseAppDistribution:appDistributionUpload gradle 命令中缺少应用程序 ID
- mysql - 跨列和行计算值的实例
- javascript - 使用 redux 钩子时使用 redux 操作的最佳选择是什么?
- sql - Impala 2.11:AnalysisException:选择列表中不支持子查询
- swift - 在 SwiftUI 中获取当前的经纬度
- c++ - 是否可以禁止一个类被动态转换为?
- git - Git - 将发布分支合并到主分支
- tensorflow - 任何想法如何解决激活函数的问题?