Category: Java

Added: 27th of October 2021

Viewed: 151 times

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

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+

Other Tips & Tutorials

Java

Install Bluej on Ubuntu, Java Development Environment for beginners

Posted: 19th of November 2021

Views: 127

Java

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

Posted: 13th of November 2021

Views: 219

Java

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

Posted: 27th of October 2021

Views: 151

Java

Printing to console in Java using the System.out.println() command, learning Java

Posted: 19th of October 2021

Views: 111

Java

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

Posted: 16th of October 2021

Views: 171