Java Program to Get Input from the User

JavaObject Oriented ProgrammingProgramming

In this article, we will understand how to get an input from user in Java. This achieved using a scanner object. The Scanner.nextInt() method is used to get the input.

The java.util.Scanner.nextInt() method Scans the next token of the input as an int. An invocation of this method of the form nextInt() behaves in exactly the same way as the invocation nextInt(radix), where radix is the default radix of this scanner.

Below is a demonstration of the same −

Input

Suppose our input is −

Hello, I am John!

Output

The desired output would be −

The input string is: Hello, I am John!

Algorithm

Step1- Start
Step 2- Declare a string: value
Step 3- Prompt the user to enter a string
Step 4- Read the values
Step 5- Display the value
Step 6- Stop

Example 1

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool run button.

import java.util.Scanner;
public class PrintString{
   public static void main(String[] args){
      String value;
      Scanner scanner = new Scanner(System.in);
      System.out.println("A reader object has been defined ");
      System.out.print("Enter a string: ");
      value = scanner.nextLine();
      System.out.println("The nextLine method is used to read the string value ");
      System.out.println("The string is: ");
      System.out.println(value);
   }
}

Output

A reader object has been defined
Enter a string: Good Morning!
The nextLine method is used to read the string value
The string is:
Good Morning!

Example 2

Here, the input is being entered by the user based on a prompt using a InputStreamReader object.

Here, the input is being entered by the user based on a prompt. You can try this example live in ourcoding ground tool run button.

import java.io.*;
public class readNum{
   public static void main(String args[]) throws IOException{
      InputStreamReader read=new InputStreamReader(System.in);
      System.out.println("An object of InputStreamReader class is created");
      BufferedReader in=new BufferedReader(read);
      System.out.println("A constructor of the BufferedReader class is created");
      System.out.println("Enter a number: ");
      int number=Integer.parseInt(in.readLine());
   }
}

Output

An object of InputStreamReader class is created
A constructor of the BufferedReader class is created
Enter a number: 34
raja
Updated on 21-Feb-2022 08:02:00

Advertisements