Programming & Scripting Tutorials

Java: User Input



I decided that with all the new stuff you guys learnt you might want to play around with a bit of user input.
The easiest way to check for user input is using the java utility "scanner"; To use this freely we use an import statement at the top of the java file like so:

import java.util.Scanner;

Ok. So next we need to create a new object for the scanner class in java utilities (just like robot1 in the class lesson):

Scanner scanner1 = new Scanner(System.in);

It's that easy, it now needs to use to input a value. In the version of netbeans I have I have to click just below "run:" in the output box and then type, but in some versions an input box comes up.

Now lets play around with the input a bit. For example we could add these lines next:

System.out.println("Enter your name:");
String name = scanner1.next();
System.out.println("Hello " + name);

Now it asks for the user's name and then says hello. There are tonnes of stuff that you can do with user input, so just start experimenting with the stuff that we've already done!

This Java tutorial was written by


Back to Java

Advertisement: