首页 > 解决方案 > 如何根据长度循环以下程序

问题描述

我添加了一个大小为 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);
        }


    }

}

标签: javaarraysloopsfor-looparraylist

解决方案


    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 击键


推荐阅读