How to read user input in Java

Azat Bayramov
2 min readNov 23, 2022

--

We use the Scanner class to read user input. It is located in java.util package. We need to import it before we use it.

Creation / Declaration Scanner Object

System.in is the parameter passed to the Scanner constructor so that Java will know to connect the new Scanner to the keyboard.

import java.util.Scanner;

public class createScannerObject {

public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);

}
}

Scanner Class Methods

Scanner Class Methods

Read Integer User Input

import java.util.Scanner;

public class getIntUserInput {

public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);
System.out.println("Enter some integer number:\n");
int num=scanner.nextInt();
System.out.println("You entered this number: "+num);

}
}

Read Decimal User Input

import java.util.Scanner;

public class getDoubleUserInput {

public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);
System.out.println("Enter some decimal number:\n");
double num=scanner.nextDouble();
System.out.println("You entered this number: "+num);
}
}

Read String User Input

import java.util.Scanner;

public class getStringUserInput {

public static void main(String[] args) {

Scanner scanner=new Scanner(System.in);
System.out.println("Enter your name:");
String name=scanner.next();

//scanner.nextLine();
System.out.println("Enter your surname:");
String surname=scanner.next();

System.out.println("Your name: "+name);
System.out.println("Your surname: "+surname);

}
}

Read String and Number Same Time

import java.util.Scanner;

public class getNumberAndString {

public static void main(String[] args) {
Scanner scanner=new Scanner(System.in);

System.out.println("Enter your age:");
int age=scanner.nextInt();

//if we use nextLine method after next method.
//we add one more nextLine method because to clear Scanner memory.
scanner.nextLine();

System.out.println("Enter your full name:");
String fullName=scanner.nextLine();

System.out.println("Full name: "+fullName);
System.out.println("Age: "+age);
}
}

Note: Please find the practice Java project on below GitHub link: https://github.com/azatbayram/GetUserInput

--

--

Azat Bayramov

Software Development Engineer in Test / interested in Blockchain