Java Program to Get Input from User

Write a Java program to get input from the user or read the given console input. We have a Scanner class in the util package, allowing us to take the console’s content. Before using this class, we must create an instance of that class and use the methods.

Java Program to Get Input from User

This program reads the user given integer, double, and float values using nextInt(), nextDouble(), and nextFloat() methods. To do so, we imported the Scanner class from the util package. Next, a private static Scanner sc line will create an instance of the Scanner class with the alias name sc. Within the class, there are many functions that include the following but are not limited to.

  • nextInt() to read an integer.
  • nextDouble() to read Double values.
  • nextFloat() to read float values, etc.
package RemainingSimplePrograms;

import java.util.Scanner;

public class UserInputs1 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter Integer Value = ");
		int x = sc.nextInt();
		System.out.println("User Entered Integer Value = " + x);
		
		System.out.print("\nPlease Enter Double Value = ");
		double y = sc.nextDouble();
		System.out.println("User Entered Double Value = " + y);
			
		System.out.print("\nPlease Enter Float Value = ");
		float z = sc.nextFloat();
		System.out.println("User Entered Float Value = " + z);

	}
}
Java Program to Get Input from User

In this Java get input from the User program, we used nextLine() to read the whole line or string, next().charAt(0) to read the first character, and nextByte() to read the byte from the console. Please refer to other Java programs to find few more Scanner functions.

import java.util.Scanner;

public class Example2 {
	
	private static Scanner sc;
	
	public static void main(String[] args) {
		
		sc = new Scanner(System.in);
		
		System.out.print("Please Enter Any String = ");
		String str = sc.nextLine();
		System.out.println("User Entered String = " + str);
			
		System.out.print("\nPlease Enter any Character =  ");
		char ch = sc.next().charAt(0);
		System.out.println("User Entered Character = " + ch);
		
		System.out.print("\nPlease Enter any Byte =  ");
		Byte b = sc.nextByte();
		System.out.println("User Entered Byte = " + b);
	}
}
Please Enter Any String = Hello
User Entered String = Hello

Please Enter any Character =  M
User Entered Character = M

Please Enter any Byte =  9
User Entered Byte = 9