-1

I've got a problem with looping a scanner, wich should return EVERY string given as an input unless String != "end". Here is what I've done so far

private static String fetchString() {
    Scanner scanner = new Scanner(System.in);
    String stringElement = "";
    System.out.println("Write a string");
    while(scanner.hasNextLine()) {
        stringElement = scanner.next();
        if(stringElement == "end") {
            break;
        }
    }
    return stringElement;
}

result:

Write a string
abc
abc
abc
end
end

Loop, somehow, doesn't understand if(stringElement == "end"), it still wants new word. I can't get it. Where am I making a mistake?

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
jas97
  • 29
  • 7
  • 1
    Please don't annotate Java code as if it were a Javascript snippet - Java and Javascript are very different. Now, you've declared a method that returns a single string - how would you expect that to return multiple strings? Also see http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java – Jon Skeet Aug 25 '16 at 11:12
  • 3
    @KevinEsche: That's *a problem* in the code, but it's not the primary one, I'd say. – Jon Skeet Aug 25 '16 at 11:13
  • To begin with, use `stringElement.equalsIgnoreCase("end")` instead of `stringElement == "end"` – iMan Aug 25 '16 at 11:14
  • 1
    Also note that you are checking for `hasNextLine` and reading a single String using `next` – TheLostMind Aug 25 '16 at 11:16
  • I return string, and then put it to the table – jas97 Aug 25 '16 at 11:18
  • yes, I have to return ONE string, and then add it to the table, but then I have to repeat that untill `string.equals("end")` – jas97 Aug 25 '16 at 11:24

1 Answers1

0

First change, stringElement = scanner.next(); to stringElement = scanner.nextLine();, second change if(stringElement == "end") to if(stringElement.equals("end"))

Stugal
  • 850
  • 1
  • 8
  • 24