ThomasV
ThomasV

Reputation: 1

How do I fix in.nextLine() returning an array of empty strings?

im very new to this, working on some ap comp sci problems i want to store user inputs into an array list of strings, but when i print the array im trying to fill, i just get something like [, , , ] how can i fix this?

public static void main(String[] args) {
    // TODO Auto-generated method stub

    System.out.println("Enter words, followed by the word \"exit\"");

    Scanner in = new Scanner(System.in);
    ArrayList<String> words = new ArrayList<String>();
    WordList test = new WordList(words);

    while(!in.next().equals("exit"))
    {
        words.add(in.nextLine());
    }

    System.out.println(words);

Upvotes: 0

Views: 144

Answers (1)

guymaor86
guymaor86

Reputation: 466

The problem you have is that in the while loop condition you read what the user typed in the input, and then inside the while you read am empty line.

You need to read the line only inside the while, and break the loop if the user typed 'exit'. As follows:

public static void main(String[] args) {
    System.out.println("Enter words, followed by the word \"exit\"");
    Scanner in = new Scanner(System.in);
    ArrayList<String> words = new ArrayList<String>();

    while (true) {
        String str = in.nextLine();
        if ("exit".equals(str)) {
            break;
        }
        words.add(str);
    }
    System.out.println(words);
}

Upvotes: 1

Related Questions