Java Program to Get Input From User

In this post, we will learn how to get input from users using Java Programming language.

We will be using the Scanner class to get input from the user. We will learn to take input of the following data types.

  1. String data type
  2. Integer data type
  3. Floating point data type

So, without further ado, let’s begin this tutorial.

Java Program to Get Input From User

// Java Program to Get Input from User
import java.util.Scanner;
public class GetInputData{
    public static void main(String[] args){
    int num;
    String str;
    float number;
    
    // Asking for input
    Scanner sc = new Scanner(System.in);
    
    // Get string input
    System.out.println("Enter a string: ");
    str = sc.nextLine();
    System.out.println("Input string is: " + str);
    
    // Get integer input
    System.out.println("Enter an integer: ");
    num = sc.nextInt();
    System.out.println("Input integer is: " + num);
    
    // Get Float number input
    System.out.println("Enter a floating point number: ");
    number = sc.nextFloat();
    System.out.println("Input floating point number is: " + number);
    }   
}

Output

Enter a string: 
CodingBroz
Input string is: CodingBroz
Enter an integer:
15
Input integer is: 15
Enter a floating point number:
12.34
Input floating point number is: 12.34

How Does This Program Work ?

    int num;
    String str;
    float number;

We have declared int, string and floating data type variables in our program.

    // Get string input
    System.out.println("Enter a string: ");
    str = sc.nextLine();
    System.out.println("Input string is: " + str);

To get string data type from the user, nextLine() method is used.

    // Get integer input
    System.out.println("Enter an integer: ");
    num = sc.nextInt();
    System.out.println("Input integer is: " + num);

To get integer data type input, nextInt() method is used.

    // Get Float number input
    System.out.println("Enter a floating point number: ");
    number = sc.nextFloat();
    System.out.println("Input floating point number is: " + number);

Similarly, nextFloat() method is used to get input of the floating data type.

Conclusion

I hope after going through this post, you understand how to get input from users using Java Programming language.

If you have any doubt regarding the program, feel free to contact us in the comment section. We will be delighted to guide you.

Also Read:

Leave a Comment

Your email address will not be published. Required fields are marked *