Reputation: 848
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.
Upvotes: 1
Views: 315
Reputation: 1242
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();
}
Upvotes: 0
Reputation: 3039
Perhaps you should be checking that the Scanner has something left to parse?
while(scanner.hasNextLine() && !input.equalsIgnoreCase("stop")) {
input = scanner.nextLine();
}
Upvotes: 1