Home | About | Categories | All Tips & Tutorials

Reading user input and outputting the results to console in Java using Scanner class

ID: 288

Category: Java

Added: 27th of October 2021

Views: 1,803

What does the code do?
The java code below asks the user to input their name and age and outputs the results in the console window.

import java.util.Scanner;

public class UserInput {

public static void main (String[] args) {

Scanner uin = new Scanner(System.in);
System.out.println("What is your name?");
String name = uin.nextLine();

Scanner uia = new Scanner(System.in);
System.out.println("How old are you?");
int age = uia.nextInt();

System.out.println("Hello " +name+ ", you are "+age+ " years old.");
}

}

Create a new file then copy and paste the code above
Save the file as UserInput.java

Next open the terminal, and enter the following command to compile the file
javac UserInput.java

A new file named UserInput.class will be created

To execute the code enter the following command
java UserInput

As I'm learning Java, I will try my best to explain what's going on in the code. Getting the terminology right is sometimes harder than the actual coding itself.
To get user input in Java we need to import the Scanner class.
import java.util.Scanner;

We create new Scanner objects and then assign them to variables. String for characters, Int for numbers.

Scanner uin = new Scanner(System.in);
String name = uin.nextLine();

Scanner uia = new Scanner(System.in);
int age = uia.nextLine();

We then output the results by using System.out.println. To output the variables we use +name+ and +age+

Related Tips & Tutorials

How to compile your Java code using the terminal in Linux, Learning Java

Install Bluej on Ubuntu, Java Development Environment for beginners

Printing to console in Java using the System.out.println command

Simple for loop in Java. Print the numbers 1 to 10 in the console