Results 1 to 4 of 4
- 11-27-2012, 03:19 PM #1
Member
- Join Date
- Nov 2012
- Posts
- 13
- Rep Power
- 0
Why won't my while loop break on command?
Hey guys. I'm new here and need help in Java. I use eclipse.
Here's some code I wrote. I want to keep inputting names until I press enter on an empty string.
Unfortunately, my loop never breaks.
import java.util.Scanner;
public class main {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String worker_name;
System.out.println("Enter names of workers: ");
int i=0;
while(i<3) {
worker_name = scan.next();
if (worker_name==null) //meaning if I press enter without writing a name it the loop should break
break;
System.out.println("His name is " + worker_name);
}
}
}
Can someone please help?
Thanks
- 11-27-2012, 03:46 PM #2
Moderator
- Join Date
- Apr 2009
- Posts
- 10,438
- Rep Power
- 16
Re: Why won't my while loop break on command?
Does it get past the 'scan.next()' call?
I thought that would block until you get some data.
In any case, worker_name won't be null, it'll be an empty String.Please do not ask for code as refusal often offends.
- 11-27-2012, 03:57 PM #3
Member
- Join Date
- Nov 2012
- Posts
- 13
- Rep Power
- 0
Re: Why won't my while loop break on command?
I figured it out. Thanks for your quick reply.
I changed it to this:
Scanner scan = new Scanner(System.in);
String worker_name=null;
System.out.println("Enter names of workers: ");
while(true) {
worker_name=scan.nextLine();
if (worker_name.length()==0)
break;
System.out.println("His name is " + worker_name);
}
- 11-27-2012, 04:32 PM #4
Re: Why won't my while loop break on command?
Why do they call it rush hour when nothing moves? - Robin Williams
Similar Threads
-
While loop wont break unless there is a print statement in it
By phillipie99 in forum New To JavaReplies: 3Last Post: 11-26-2012, 11:06 AM -
Interrupt loop without break or continue
By mwr1976 in forum New To JavaReplies: 2Last Post: 10-12-2011, 03:43 AM -
break or stop for loop
By mitra in forum New To JavaReplies: 7Last Post: 09-12-2011, 11:39 PM -
Loop through an Array and invoke SQL command
By Robert_85 in forum JavaServer Pages (JSP) and JSTLReplies: 3Last Post: 04-25-2010, 12:14 PM -
Counting with a delayed loop and using button to break
By danmc in forum New To JavaReplies: 1Last Post: 03-03-2009, 12:46 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks