Results 1 to 2 of 2
  1. #1
    lowziqian is offline Member
    Join Date
    Nov 2011
    Posts
    4
    Rep Power
    0

    Default Whats wrong with my while loop?

    the task is to let the user input item code, and quantity he wants until he inputs "XX" to terminate the looping.
    but my code seems to stop at one loop.
    Q: do i have to use an array? or is it a logic problem? ( i will have to use the string inputs in the later part)
    ps: i do not want an answer, i just want to know what misconception i have.


    System.out.println("ENTER CODE (XX to Stop):");
    System.out.print("CODE: ");
    String i=scan.nextLine();


    while(!i.equals("XX"))

    {

    System.out.println("ENTER QUANTITY: ");
    int y=scan.nextInt();
    System.out.println("ENTER CODE :");
    i=scan.nextLine();
    }

  2. #2
    JosAH's Avatar
    JosAH is online now Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,763
    Blog Entries
    7
    Rep Power
    21

    Default Re: Whats wrong with my while loop?

    There's nothing wrong with your while loop; it's the nextInt() method that's acting up; that method only reads digits but if you type in a number, say 42, you type '4' '2' and <enter>. The nextInt() method leaves the <enter> character(s) in the input buffer so the following nextLine() method assumes that it just read an empty line. The idiom is to add a dummy readLine() call just after you have read a number to get rid of that <enter> character in the input buffer.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

Similar Threads

  1. Whats wrong with my code
    By zit1343 in forum New To Java
    Replies: 9
    Last Post: 01-24-2011, 02:06 AM
  2. Whats wrong with my program?
    By jwb4291 in forum New To Java
    Replies: 7
    Last Post: 12-12-2010, 05:40 AM
  3. whats wrong
    By atenv in forum New To Java
    Replies: 6
    Last Post: 06-15-2010, 02:55 PM
  4. whats is wrong with this app??
    By mrajan in forum New To Java
    Replies: 4
    Last Post: 06-09-2010, 11:56 PM
  5. Database help... whats wrong?
    By neosnokia in forum JDBC
    Replies: 4
    Last Post: 06-10-2009, 12:17 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
  •