0

I have added a for loop in size of 3 it should scan for 3 times but it is scanning for 4 time.for size of 4 its scanning for 6 times help me out.

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);
        }


    }

}

1 Answers1

1
    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 does not account for the enter that you press when you submit the int so you have to catch the unused enter keystroke