Results 1 to 4 of 4
  1. #1
    juhess88 is offline Member
    Join Date
    Nov 2012
    Posts
    13
    Rep Power
    0

    Default 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

  2. #2
    Tolls is online now Moderator
    Join Date
    Apr 2009
    Posts
    12,008
    Rep Power
    20

    Default 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.

    ** This space for rent **

  3. #3
    juhess88 is offline Member
    Join Date
    Nov 2012
    Posts
    13
    Rep Power
    0

    Default 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);

    }

  4. #4
    DarrylBurke's Avatar
    DarrylBurke is online now Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,237
    Rep Power
    19

    Default Re: Why won't my while loop break on command?

    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

Similar Threads

  1. Replies: 3
    Last Post: 11-26-2012, 11:06 AM
  2. Interrupt loop without break or continue
    By mwr1976 in forum New To Java
    Replies: 2
    Last Post: 10-12-2011, 03:43 AM
  3. break or stop for loop
    By mitra in forum New To Java
    Replies: 7
    Last Post: 09-12-2011, 11:39 PM
  4. Loop through an Array and invoke SQL command
    By Robert_85 in forum JavaServer Pages (JSP) and JSTL
    Replies: 3
    Last Post: 04-25-2010, 12:14 PM
  5. Replies: 1
    Last Post: 03-03-2009, 12:46 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •