• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

java.util.Scanner Problem

 
Ranch Hand
Posts: 92
Android
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Question : when i run the code its skipping one user Input i.e  First two work fine but third one appear like    Enter Your University Name : Enter your Country Name :   and i can't enter the university name !! How to solve this Error ! For me i user Scanner class for every user Input in this case i user four classes of Scanner to Over Come !!


 
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It isn't skipping anything. You are also giving the wrong error. You finish before you reach country name.
Please tell me what your book says nextLine() does, then I shall show you the solution.
 
Saad Zahoor
Ranch Hand
Posts: 92
Android
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i should do it without typing next ?
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No.
That is simply guessing. You can make 1,000,000 guesses and one will be correct, or you can answer my question and I shall show you the explanation.
 
Saad Zahoor
Ranch Hand
Posts: 92
Android
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
nextLine () take the string input from the user !! now i understand i have to do it without typing Line .. only next will work ! thanks for opening my brain .. but whats the logic behind it ?
 
Rancher
Posts: 4801
50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
With next() try using a University name like Liverpool John Moores.
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
No, that isn't the right explanation. You will find the explanation and a possible solution here. There is more discusison and a possible different solution to your problem from Lisa Austin and Liutauras Vilda here.
Simplest solution: add this code as line 9½:-
userInput.nextLine();
Don't use \n. Use printf and the %n tag.
 
Saad Zahoor
Ranch Hand
Posts: 92
Android
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
yup ! its working with next ()
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Saad Zahoor wrote:yup ! its working with next ()

No, it isn't, as you will see if you follow Dave Tolls' suggestion.
 
Saad Zahoor
Ranch Hand
Posts: 92
Android
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
yea .. You are right . its not working . This time it is not asking me about the country and printing the result !
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have already given you a solution. Why didn't you try that?
 
Bartender
Posts: 1971
17
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:I have already given you a solution. Why didn't you try that?



Agreed. Part of being a Java developer is learning to read documentation and the literally TONS of examples online.

And, since Java is #1, there are so many examples on how to do virtually anything, it's difficult NOT to find a solution. Plus, with the Ranch, you'll find expert help, but not necessarily people writing the actual code for you.

-----

A simple solution to your issue is below. You could also use next() to read each token individually.

 
===

Prints out:

Enter Your Name : Java Developer
Enter Your Age : 101
Enter Your University Name : Java University
Enter your Country Name : USA

Java Developer
101
Java University
USA



---

If you don't already, get a good Java book like the Deitel "Java, How to Program". It's chalked full of useful examples.

 
Saad Zahoor
Ranch Hand
Posts: 92
Android
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Just wanna ask what Integer.parseInt do and why use nextLine () . isn't it use for the String Input ?
 
Mike London
Bartender
Posts: 1971
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Saad Zahoor wrote:Just wanna ask what Integer.parseInt do and why use nextLine () . isn't it use for the String Input ?



Did you read my posting at all?

Look it up.
 
Sheriff
Posts: 7125
184
Eclipse IDE Postgres Database VI Editor Chrome Java Ubuntu
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Integer.parseInt is used to parse (analyse) a String and see if it is an integer.  If it is, it returns that integer.  If not, it throws an exception.

Why you use nextLine() is complicated, but here goes: Scanner parses its input into tokens.  The default is that tokens are separated by whitespace.  When you type something into Systm.in and hit Enter, you get an input like this "123\n".  Scanner.nextInt() looks for the next integer and "consumes" it, but not the newline (\n) at the end.  Scanner.nextLine() consumes an entire line, newline and all.  So when you do and nextInt(), you leave a newline in the input.  Then nextLine() sees that newline and you get an empty string.  Calling nextLine() twice consumes the leftover newline, then looks for your entered text.
 
Saad Zahoor
Ranch Hand
Posts: 92
Android
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Actually , my mother language is not English !! It's getting hard to understand this thing  . But thanks mate for elaborating it .But i would like to move forward by just remembering this line of code  
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Likes 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike London wrote:. . . A simple solution to your issue is below. You could also use next() to read each token individually.

  . . .

Although that solution will work, I don't think it is the best use of a Scanner. If Scanner has the ability to parse the int directly, I would use it, with nextInt().
The problem is a method whose documentation tells you exactly what it does, clearly and simply. But it has a misleading name. It is poorly documented in many books, which say it returns the next line. There are few places where you will find documentation telling you how to sort out the problem of its returning an empty String. Following next() by nextLine() won't sort out the empty String problem.
Of course, you make things worse for yourself if you are given links and don't read them, or if you are given hints and don't believe them.
 
Mike London
Bartender
Posts: 1971
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yep, I was just showing one way to get the output he wanted with no skipped inputs.

The next thing you might want to do is read data from an actual file, not just from the command line.

Say your input text file looks like this (names randomly generated with random text generator):

Marti Billiar 83 My University USA
Chadwick Arizzi 82 Your University
Serina Yanchik 50 Some other University


--------------------------

The code to process it might look like that below and could be further optimized.

In practice, you wouldn't probably use a StringBuilder, but I'm using it to demonstrate that you shouldn't concatenate strings with "+", for performance reasons, when possible.

Obviously, you could do whatever you needed to with each token when read from the file. I'm just reading them and storing them below.



Output:

Marti Billiar 83  My University USA
Chadwick Arizzi 82  Your University
Serina Yanchik 50  Some other University


Java is so cool!!!

- mike
 
Mike London
Bartender
Posts: 1971
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Or, using Java 7 try-with-resources (same output):

 
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Only use \n if somebody has requrested the LF character. For the name at the beginning, I would suggest you use myScanner.hasNextInt(), or more precisely
while (!myScanner.hasNextInt())
which will get you as far as the 83 in the first line. What is going to happen when the name of the country isn't a single word, I shall leave to you to sort out. Or when the program fails to notice there isn't a country name in line 2.
Random text generator? That looks interesting. Is it a sort of PhraseOMatic (à la Head First Java)?
 
Mike London
Bartender
Posts: 1971
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thanks Campbell.

Yeah it was a quick example tailored to the file I created.

For the random data generator, check out "Randommite". It's not really supported anymore that I'm aware of but it's pretty nice.

- mike
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Randommite appears still to be available for download, but it only says for MacOS.
 
Mike London
Bartender
Posts: 1971
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:Randommite appears still to be available for download, but it only says for MacOS.



What?! You mean you're NOT on a Mac? ;)

Regarding your comments above, I don't see myself ever using a Scanner class for a production file import, but to handle spaces throwing off the fields and such like you pointed out as a potential problem, one solution would be to include sentinel characters joining words and then strip them out in the Java code. But that begs the question, why not just use a CSV to begin with? Not sure if anyone still uses the now-archaic SDF file, but that could be another option. Java's file I/O library is so rich, there isn't much (anything?) you can't do.

Still not sure why I used the StringBuilder. Just to avoid string concatenation I guess. The final  "\n" was just for display. In a "real" utility, I wouldn't use it.

Thanks for your great replies.

The ranch rocks!

- mike
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Mike London wrote:. . . What?! You mean you're NOT on a Mac? ;)

Are you telling me there are still people who don't use Linux?

. . . spaces throwing off the fields and such like you pointed out . . . sentinel characters joining words . . . why not just use a CSV to begin with?

A Scanner would work like that, but it would be dependent on the file's having a predictable and reproducible sequence of tokens. Surely sentinel characters would be simply a different variant of a CSV. Well, the same concept anyway. A pipe‑separated file only differs from a CSV in using | rather than commas.

Not sure if anyone still uses the now-archaic SDF file

Never even heard of SDF.

. . . Java's file I/O library is so rich, there isn't much (anything?) you can't do.

So is the Collections Framework. That is one of the places where Java® got ahead of many other languages, setting the bar higher for anybody wanting to write a similar platform later on. Even if there are specialised requirements which the Collections Framework doesn't address properly, but Apache Commons deals with many of them.

Still not sure why I used the StringBuilder.

Possibly because StringBuilder#append is more efficient than the + operator in multiple lines.

. . . The final  "\n" . . . In a "real" utility, I wouldn't use it.

You know that, but many of the other people here don't know that, and there are books which show \n on every page, so it needs warning against.

Thanks for your great replies.

The ranch rocks!

- mike

What a nice thing to say. Thank you. And, “You're welcome.”
 
Mike London
Bartender
Posts: 1971
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The "SDF" file, or as it was called when I used it as a file transfer mechanism a long while back was simply a file where all the fields were against each other and you needed a separate "legend" to tell you how to extract the fields.

So, for example ...

MikeLondon123SomwhereStreetSomeCitySomeStateSomeZip

with a corresponding file like this:

Full name: 1-10
Address:  11-27
etc.

---

Probably a by-gone mainframe type file. Haven't seen any of these in a long time

Thanks,

- mike
 
Campbell Ritchie
Marshal
Posts: 79179
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That can easily be parsed with substring(). I have forgotten most of my SQL but maybe that is how a VARCHAR is implemented.
 
Mike London
Bartender
Posts: 1971
17
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Campbell Ritchie wrote:That can easily be parsed with substring(). I have forgotten most of my SQL but maybe that is how a VARCHAR is implemented.



Sure, but I was only answering your point about what an SDF file was.

- mike
reply
    Bookmark Topic Watch Topic
  • New Topic