1
Scanner scanner = new Scanner(system.in);
String input = new String();

while(!input.equalsIgnoreCase("stop")) {
input = scanner.nextLine();
}

Why is this not working? The loop lasts forever. I have used this method a million times before and now it wont work.

EDIT**

Okay I am using JGrasp (as this is what my professor wants us to use) and when I tried this in netbeans it worked fine...

EDIT2**

First of all I am not sure whether or not this is the problem but in my code I had something like this towards the beginning of main Scanner scanner = new Scanner(file); And later on something like this scanner = new Scanner(System.in); and that is where the previous code snippet starts off. So first of all I changed this by having main call a new method for the area where I needed the while loop with string checking. And I also reformatted the loop:

Scanner scanner = new Scanner(System.in);
    String input = new String();

    while(!input.contains("stop")) {
        System.out.print("Enter an option: ");
        input = scanner.nextLine();
    }

And now it works fine.

EDIT3**

So I tried the original format inside the new method and it also works perfectly. I believe now that it has something to do with how I had a scanner for the file and then reused that reference for a new scanner object with System.in. I am not 100% on that, but moving the while loop to a method of its own and not keeping it in main worked, so I feel like it has something to do with that.

2
  • The input line has to precisely equal "stop". It can't have an extra tab, space, non-printable unicode character, or anything else. Commented Oct 8, 2012 at 5:54
  • 2
    Just guessing - input.trim().equalsIgnoreCase("stop")? Commented Oct 8, 2012 at 5:58

2 Answers 2

1

Perhaps you should be checking that the Scanner has something left to parse?

while(scanner.hasNextLine() && !input.equalsIgnoreCase("stop")) {
    input = scanner.nextLine();
}
Sign up to request clarification or add additional context in comments.

1 Comment

This is actually input by the user and not a file or anything, so the scanner would always have something left to parse...to the best of my knowledge.
0

Code is working fine: Except an compilation error i.e please use System.in instead of system.in

Scanner scanner = new Scanner(System.in);
String input = new String();

while(!input.equalsIgnoreCase("stop")) {
    input = scanner.nextLine();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.