Continuously get user's input until an empty string is entered
Again, I seem to find myself in a web of simple but difficult to figure out what the problem is. I have the code below that just keeps getting the user's name and displaying it until the user enter's an empty string. Well, to simulate that, I just hit the keyboard instead of entering any name but for some reasons I am not seeing in my code, the programme just keeps looping. Any help on this?
Code :
System.out.println("Enter your name : \n");
Scanner st = new Scanner(System.in);
while(st.hasNext()){
System.out.println("Enter your name : \n");
String name = st.nextLine();
System.out.println(name);
if(name==" ") break;
}
System.out.println("you are out of the while loop now!!");
Re: Continuously get user's input until an empty string is entered
Dont compare strings with "==", you HAVE to use the equals() method to compare Strings.
Re: Continuously get user's input until an empty string is entered
Hi, even when I do the comparison :
Code :
if(name.equals(" ")) break;
It still doesn't get out of the loop.
Re: Continuously get user's input until an empty string is entered
That's not an empty String, that's a String with a space in it.
Do:
Code java:
if(name.trim().equals(""))
name.trim() will remove any leading or trailing spaces, and "" is an empty String. So this will evaluate to true if the String is empty or just a space.
Re: Continuously get user's input until an empty string is entered
Did you enter a single space character or an empty string? Because these two are not the same:
Re: Continuously get user's input until an empty string is entered
When I tried this..the programme still keeps running in the loop for a while..before breaking out of the loop. How can I modify the code in such a way that immediately I enter "" in the input, the programme exits the while loop and goes to the next statement:
Code java:
System.out.println("you are out of the while loop now!!");
Code java:
System.out.println("Enter your name : \n");
Scanner st = new Scanner(System.in);
while(st.hasNext()){
System.out.println("Enter your name : \n");
String name = st.nextLine();
System.out.println(name);
if(name.trim().equals("")) break;
}
System.out.println("you are out of the while loop now!!");
Re: Continuously get user's input until an empty string is entered
Try putting the "if" expression at the top of the loop so it
is executed/checked against before any of the loop code is
executed. Also, place the expression in braces so it belongs
in it's own field of scope.
If none of these work then you are going to have to re-write your
continuation condition of the said loop - so it will only execute when
valid input is entered before the loop is reached.
Wishes Ada xx