0

When adding items using the while loop to the List, it is possible to interrupt it by clicking "q". Unfortunately, it does not display all elements of this List. Every second item is displayed and not always the letter "q" will work the first time.

Thanks for any help in solving this problem.

// ListOfStudents class:

package collections;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class ListOfStudents {
    private List<String> names;

    public ListOfStudents() {
        System.out.println("Enter students name or press 'q' to quit: ");
        this.names = listOfStudents();
    }

    private List<String> listOfStudents() {

        names = new ArrayList<>();

        while (!getName().equals("q")) {
            names.add(getName());
        }

        for (String s : names) {
            System.out.println(s + " ");
        }
        return names;
    }

    private String getName() {
        Scanner in = new Scanner(System.in);
        return in.nextLine();
    }
}


// Main class:

package collections;

public class Main {

    public static void main(String[] args) {

        ListOfStudents listOfStudents = new ListOfStudents();

    }
}

I tried changing the loop to a for loop and setting the number of iterations to 5 and it works. I wanted to be able to set this List to any length, so I use a while loop.

Łukasz K
  • 9
  • 2

0 Answers0