Jump to content

Problem with next() and nextLine()

- - - - -

  • Please log in to reply
3 replies to this topic

#1
arnes99

arnes99

    Learning Programmer

  • Members
  • PipPipPip
  • 32 posts
Hi! Could you explain it to me why this problem of mine happens:
This code:
//Some code up here...

Scanner s = new Scanner(System.in);

System.out.println("Database URL: ");
dbURL = s.next();
System.out.println("User: ");
user = s.next();
System.out.println("Password: ");
passwd = s.next();

//Some code here...

String name;
String quantity;
String price;

System.out.println("Name: ");
name = s.nextLine();
System.out.println("Quantity: ");
quantity = s.next();
System.out.println("Price: ");
price = s.next();

//More code here...
This code works BUT at the time when the user should get a "Name:" printed on console and waiting for a user's input (a line) and then print Quantity: and so on, instead of that, I get Name: and then
immediately Quantity: and when I enter something in fails to input this into database.
It has something to do with these variables and next(9 and nextLine() methods.
I think I came upon once with a similar problem in C++ and the problem was with \n that remains in buffer or something like that.

Not until I comment out the users input for database url, username and password and hardcode these database information into code does the program work correctly.

#2
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
When you enter this:
"http://url.com/url"
You propably enter afterwards to send it on, but that enter is also waiting for the scanner to be read, so what you actually type in is:
"http://url.com/url\n"
The scanner's next() method decides that the next input goes up to the "\n" and it returns the URL properly.
Your proplem is that "\n" is still waiting to be read. And when you do .next() again, it immediately finishes and returns the "\n" instead of waiting for proper input.

So you can either do a next() again after every next() you WANT to do.
Or, cleaner solution, tell the scanner to do it properly :P

Scanner scanner = new Scanner(System.in).useDelimiter("\\n");        



#3
arnes99

arnes99

    Learning Programmer

  • Members
  • PipPipPip
  • 32 posts
Thanks wim DC. That makes sense. Now I don't have to hard code my database data in a program. +1 REP

#4
wim DC

wim DC

    Writes binary right handed and hex left handed

  • Members
  • PipPipPipPipPipPipPipPipPip
  • 2,084 posts
  • Programming Language:Java, JavaScript, PL/SQL
  • Learning:Java
Oh, I forgot the easiest / most used solution ^^
Use nextLine(); instead of next();




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users