Java Input using

Lagre Download example files

We will now allow a user to enter his name and age to a program. We do this by receiving data from the keybaord.

When we want to receive data from a user, we need to use something called Scanner. The scanner is a bit difficult to use. You need to import it in the start of your code.

Create a new project and give the project name Input.
01_nytt_prosjekt.gif 02_type_prosjekt.gif 03_prosjektnavn.gif

At the very start write

Scanner scanner = new Scanner (;

There will be red lines under the code. Import a class called Scanner to remove the red lines. This is done by having the cursor over the word Scanner and press ALT+Enter.

You will then get a menu with various choices. Select "Add import for java.util.Scanner".


We can now write the rest of the code. We ask for name and age. Then we print the results.

// Scanner class
Scanner scanner = new Scanner (;
// Ask for name
System.out.println("What is your name?");
String name =;
// Ask for age
System.out.println("How old are you?");
String age =;
// Print result
System.out.println("Name: " + name + ". Age: " + age);



1. Create a program that asks for name, age and residence. Print the result.

2. Create a program that asks for name and surname. Print the result.

3. Write a program that receives the user's date of birth. The birth date will be stored in three variables: bornYear, bornMonth og bornDay.
Use nextInt instead of next:
int bornYear = scanner.nextInt();
int bornMonth = scanner.nextInt();
int bornDay = scanner.nextInt();

Can you create a formula that calculates the age of the user with this information?

Add comment






No comments yet. You can be the first one to comment. Just write your comment in the form and click on the submit button.