Java Scanner Help - Common Questions And Answers

Looking for Java Scanner help?

I've gotten some questions on the Java Scanner class. Depending on what you're trying to accomplish with it, you may experience some difficulty working with it. This is ok. The Java Scanner didn't even exist until Java version 1.5.0, so even to those who have been programming in Java for a while may be unfamiliar with the nuances of working with this peculiar class.

Here are some common questions I have received in the past and the answers to those questions. I hope this helps you, and if you don't see your particular question, please use the contact form at the bottom of this page and I'll make sure to include it.

Q: What happens if I scan a blank line with Java's Scanner?

A: It depends. If you're using nextLine(), a blank line will be read in as an empty String. This means that if you were to store the blank line in a String variable, the variable would hold "". It will NOT store " " or however many spaces were placed. If you're using next(), then it will not read blank lines at all. They are completely skipped.

Q: How do I select a word with a Java Scanner?

A: Use next() to read in the data one word (or characters up until a space is reached) at a time.

Q: How do I keep my input on the same line?

A: If you input the data all on the same line, you can use nextLine() to grab the data and store it all on a single String.

Q: How do I repeat an input with the Scanner?

A: This is not so much a problem with Scanner itself. If you want to keep getting input, make sure to put some kind of loop around where you're grabbing input. You can use a for loop or a while loop to accomplish this. I suggest reading the for loop and while loop tutorial if you're not sure what they are or how to use them.

Q: Why won't my Scanner work? It won't read the line at all?

A: Make sure that if you use a Scanner to do a nextInt(), you can no longer use that same Scanner to perform a nextLine() for waiting on input. It will not work as it will read the newline from the integer input. A workaround is to just create another Scanner so you have two, one for inputting integers and the other for inputting text.


Click here to sign up to our free newsletter today to get more free Java tips, sample programs, and much much more delivered to your email monthly! It'll also contain even more answers to your questions so don't miss out!

Contact Us!
Please note that all fields followed by an asterisk must be filled in.
First Name*
Last Name
E-mail Address*
Question or Comment

Please enter the word that you see below.

  

Custom Search