Java Program to Take Input From User - The Coding Shala

Home >> Java Programs >> Take User Inputs

 Hey there, welcome back to another post. In this post, we are going to learn how to take inputs from the user in Java.

Java Program to Take Input From User

Here, we are going to use the Scanner class to take user input. We will use the below methods:

  • For integer: nextInt()
  • For long: nextLong()
  • For float: nextFloat()
  • for double: nextDouble()
  • for String: next()
  • for complete line: nextLine()
Java Program: 

import java.util.Scanner;

/**
 * https://www.thecodingshala.com/
 */

public class Main {

    public static void main(String[] args) {
        // using Scanner class
        Scanner sc = new Scanner(System.in);

        // taking integer inputs
        // for integers use nextInt()
        // for long use nextLong()
        System.out.println("Enter integer");
        int num1 = sc.nextInt();
        System.out.println("Entered integer is: " + num1);

        // taking float/Double input
        // for float -> nextFloat()
        // for double -> nextDouble()
        System.out.println("Enter float");
        float num2 = sc.nextFloat();
        System.out.println("Entered float is: " + num2);

        // taking string input using next()
        System.out.println("Enter a string");
        String str = sc.next();
        System.out.println("Entered string is: " + str);

        // taking complete line as string input using nextLine()
        // it will move the cursor to the next line
        System.out.println("Enter a string with spaces in between");
      //  String str2 = sc.next(); -> this will take only first word
        sc.nextLine(); // this will move current cursor to the starting of next line
        String str2 = sc.nextLine();
        System.out.println("Entered string is: " + str2);
    }
}

Output: 

Enter integer
5
Entered integer is: 5
Enter float
3.5
Entered float is: 3.5
Enter a string
Akshay
Entered string is: Akshay
Enter a string with spaces in between
Hello Akshay, How are you?
Entered string is: Hello Akshay, How are you?


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala

Add two numbers in Scala - The Coding Shala