0

I was trying to read the following input from the user I need to save the input as a string of words but with no duplications and it stops taking input when it hits "zz".

input example

but my code does not read watermelon and strawberry and I do not know why or how to fix it. Every time if there is a bunch of leading spaces my code ignores the word and goes for the one next to it.

This is my code

String text="";
while (keyboard.hasNext()) {
    String word = keyboard.next().trim().toLowerCase();
    if (!word.equals("zz")) {
        if(!text.contains(word)) {
            if (text.length()==0) {
                text=word;
            }
            else {
                text+=" "+word;
            }
        }
    }
    else {
        keyboard.close();
        break;
    }
}

  • change `hasNextLine()` to `hasNext()` this will solve the issue with strawberry – Ofek Aug 06 '21 at 06:02
  • I did but it shows the same issue. – JavaBeginner Aug 06 '21 at 06:06
  • Basic rule: Always read the whole line at a time with `nextLine()` and parse it yourself programatically. You actually gain nothing by using `next()`, but you introduce lots more code and even more confusion. – Bohemian Aug 06 '21 at 06:09
  • When I run it, I don't see any issue, can you put all the code you wrote? – Ofek Aug 06 '21 at 06:11

0 Answers0