Results 1 to 4 of 4
  1. #1
    fiction is offline Member
    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    Default problem with scanner

    hi people. i recently started with java and stuck on one thing.
    i was doing something with scanner and noticed a problem


    Scanner entry = new Scanner(System.in);
    double stnm, ndnm, res;
    System.out.println("Enter 1st number: ");
    stnm = entry.nextDouble();
    System.out.println("Enter 2nd number: ");
    ndnm = entry.nextDouble();
    res = stnm+ndnm;
    System.out.println(res);
    System.out.println("Hi. What's your name?");
    String a = entry.nextLine();
    System.out.println("Hi "+a);

    why does scanner skip this line
    i can enter first 2 integers but when i should be able to enter string it just skips that line.
    why is it so? how can i fix that?




    ty

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

    Default Re: problem with scanner

    Before you want to read an entire line, you wanted to read a double; the nextDouble() method does just that and it doesn't read an end-of-line character that most likely was typed by you. The nextLine() method does see that end-of-line character and assumes that it had read an empty line. The remedy is simple: after the last nextDouble() call, call nextLine() to get rid of that empty line.

    kind regards,

    Jos
    cenosillicaphobia: the fear for an empty beer glass

  3. #3
    Slick Java is offline Member
    Join Date
    Dec 2012
    Posts
    11
    Blog Entries
    1
    Rep Power
    0

    Default Re: problem with scanner

    Try this:

    String a = entry.next();

  4. #4
    fiction is offline Member
    Join Date
    Feb 2013
    Posts
    2
    Rep Power
    0

    Thumbs up Re: problem with scanner

    Well cheers guys.. both of your solutions worked
    thank you

Similar Threads

  1. max and min scanner problem
    By jwl in forum New To Java
    Replies: 2
    Last Post: 10-28-2012, 07:57 PM
  2. Problem with the Scanner
    By Maretaga in forum New To Java
    Replies: 6
    Last Post: 07-14-2011, 09:14 AM
  3. Scanner problem.
    By keo in forum New To Java
    Replies: 6
    Last Post: 04-07-2011, 08:30 AM
  4. Problem with scanner
    By JavaJ in forum New To Java
    Replies: 6
    Last Post: 03-16-2010, 08:51 PM
  5. Problem with scanner
    By Kangaroo128 in forum New To Java
    Replies: 11
    Last Post: 09-01-2009, 08:07 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
  •