Java Input - Using Java Scanner


Note: If you're looking for Java Scanner help, click here. The page contains some common questions about them and a question form where you can ask your own questions about Scanners in Java. Otherwise, for a Scanner example scroll down near the bottom of the page. Otherwise, simply follow along with the tutorial. The screen shots throughout are of the Eclipse IDE. If you don't have Eclipse, I highly recommend downloading it!

Want to get more tips and more personalized help on Java Scanner and other Java topics? Need help with common problems found on quizzes, tests, or other exams? Click here to sign up for the Fresh Cup Of Java Newsletter, a monthly e-zine full of sample programs, general tips, and other Java related materials, free of charge!

A Java Scanner is the fastest, easiest way to get input from a user in Java.

By this point you should be able display some sort of output onto the screen. You should also be able to store data inside of variables. Both of these concepts are great, but what's the point of a program that has no interaction with a user?

For example, what good is a computer game if you can't control any of it? What we need is input, and Java has plenty of ways of accepting input. However, we'll be using a Java Scanner for this tutorial. We're also going to deal with the simplest kind, text input. This means that we'll be inputting from the keyboard.

Note: Looking for Java Scanner help? Check out these frequently asked Scanner questions!

Getting Input

So, first thing's first, we're going to create a new class (a new Java file). If you already have a Java project in Eclipse, then all you have to do is right click on the src folder and hit new class. If you do not have a Java project, you will need to create one. If you don't know what I'm talking about, you really need to read this tutorial. It will teach you everything you need to know to get started with writing a program.

Call your new class Inputs. Remember, the class must start with a capital letter. Next, make sure to checkmark the box that adds public static void main(String[] args). If you do not, that's ok, but you'll have to add it in manually. When you've entered the name for your new class, hit finish and you should see this:

There may also be some comments in there that are green and blue (mine did not have those), and you can delete those if you want or leave them alone.

Now we're going to be doing all of our work inside of main. To make sure you're up and running, add a print line inside of the main as shown below (remember, this means in between the opening and closing curly brackets that belong to the main):

You should know how to do this basic output by now. Make sure that your program runs. You should have seen Inputs on the bottom panel of the screen.

Okay, so now onto inputting. First of all you will need to use a Java Scanner that will get this input for you. It acts like a variable but it's not one of the basic types that were talked about in the previous tutorial. Add this line into the main:

It is EXTREMELY important that you get the capitalization correct, or this will not work.

You will also notice that Eclipse has underlined Scanner in red, as shown in the next screenshot. That means that Eclipse sees this as an error. That is okay, because the code is actually missing something important.

To fix this, right click on the main screen, go down to where it says Source, then select Organize Imports. This will import everything that your program is missing. If a box pops up asking you to choose a type to import, choose java.util.Scanner. This is the correct import for the Java Scanner, as opposed to some other Scanner that might exist. For me it was the first option.

You'll notice that the following line was inserted after you organized your imports:

The Java Scanner class is like any class you create, except it was created for you. Since Java already comes with it, it had to be imported.

If you don't want to use the shortcut for importing classes, you can always just type in the import statement manually at the top of the page before the public class line. More on this for a future article though.

What we need to know for this tutorial is that we have a variable called scan, and it is a Scanner. Just like int num = 3; means that num is an int, Scanner scan = new Scanner(; means that scan is a Scanner. It's pretty simple. Don't worry too much about what it equals, it just means that it will be getting our input. Notice how it looks awfully similar to System.out but with an "in" instead.

Just because we have this variable "scan" that will take input does not mean that's all we need to be able to get some input. We have to make it accept some input. To do this, put this line of code right under the line where you create the variable scan:

This will receive the input of the next line of text someone types into the keyboard. It's pretty simple. Now, how can we use the Java Scanner to receive the line of text from a user? Well, we'll need to use a variable. If you're not up to speed on these, you'll need to go take a look at the previous tutorial.

Okay, so now we're going to create a String variable, and we're going to make it be equal to the input we get. Change the line you just wrote to:

Keep in mind that the names of my variables are my preference. You could easily just do:

It's up to you to choose what to name your variables, but in general you should try to make them as descriptive as possible while keeping them short.

Okay, so now the input someone types in will be stored in your String variable from the Java Scanner. You can use that variable to now output back the line of text. The program will just echo whatever is typed in. You should be able to output the string on your own, because you should have learned how to already. Go ahead and write the code to do this.

If you did it correctly, you wrote this under the previous line of code:

That will print the input you received using scan.nextLine();. Go ahead and try running the program. When it runs, you'll have to type in the input yourself. To do this, go to the bottom panel where you normally receive your output, and type on the first blank line you see (if stuff is printed there, you need to go down to the first blank line and begin typing). When you hit enter, Java should print out exactly what you typed. Neat stuff.

Note: nextLine() will read lines one at a time, including white spaces! If you want to skip all white space, use next() instead. Next() will read up to the first white space and then stop. If you do next() again, it will skip over the white space and continue reading the next set of characters and stop at the next white space, etc.

scan.nextLine(); will input all the text that was typed up to the point where the user hits the enter key. It's a quick and easy way to get input and to store it into a String.

Other Inputs

There are other ways of getting input. We can use scan.nextInt(); to get an integer from the user and store it in an int variable. Like this:

Now num has the integer that the user typed. If the user types in something other than an integer, the program will crash, so you must be careful. There are ways of dealing with these kinds of errors but as with a lot of details, it's beyond the scope of this tutorial. To print this num variable you do as you normally would for any int variable.

Using Both Input And Output

Now that we can do both input and output, let's make a little addition program that makes full use of the Java Scanner class. The program will ask the user to type in a number, ask the user to type in a second number, and then display the addition of the two numbers.

You can create a new Java class or you can just delete everything inside of the main method you're working with now(everything in between main's two curly brackets). If you're making a new file, name the class whatever you want, as long as the first letter is capitalized.

To begin, we must ask the user to type in the first number to add. This means you will output a question for the user onto the screen. You know how to do this, so do it.

Next, we will have the user input the number. Remember how to do this? First, we need to create the Scanner variable:

Remember to right click on the main page, select source, and then select organize imports. Next you need to create an int variable to store the first input.

Now repeat the process to ask for the second number. Remember to create a new int variable and to call it differently than the other integer variable you created.

Last, do the addition, and output the result. Do you remember how?

I'll skip some lines before spoiling the answer.

If you do not remember how to do all of this, I suggest rereading the previous tutorials as it is VITAL to get these basic concepts. Notice how I did not create two Scanner variables; you only need one to do all inputs.

Also notice the last line of code above. Remember our trick of adding strings together? Well, that's an example of adding a string and a number together. The variable has no quotes because it is a variable. But wait? Isn't num3 an int? Yes, and remember we do not need quotes to print out ints, so this would work anyway. Easy and useful isn't it?

The Java Scanner can do nextDouble() instead of just nextInt(); if you want decimal numbers. It also has a lot of other options that I won't discuss here, but keep that in mind.

Oh, one last thing, don't try to scan text with nextLine(); AFTER using nextInt() with the same scanner! It doesn't work well with Java Scanner, and many Java developers opt to just use another Scanner for integers. You can call these scanners scan1 and scan2 if you want.

So there you have it, that's how you get input using a Java Scanner. I strongly suggest playing around with what you learned and try to make your own little program that accepts user input. In the next tutorial we'll learn how to make decisions with the user's input.

If you have any questions, comments, or concerns, feel free to contact us.

Custom Search