Java Program to Read The Number From Standard Input

JavaObject Oriented ProgrammingProgramming

In this article, we will understand how to read a number from standard input in Java. The Scanner.nextInt() method is used to read the number. 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 −

55

Output

The desired output would be −

The input value is 55

Algorithm

Step1- Start
Step 2- Declare an integer: value
Step 3- Prompt the user to enter an integer value/ define the integer
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 PrintNumber{
   public static void main(String[] args){
      int value;
      System.out.println("Required packages have been imported");
      System.out.println("Variable to store value is defined");
      Scanner reader = new Scanner(System.in);
      System.out.println("A reader object has been defined\n");
      System.out.print("Enter a number: ");
      value = reader.nextInt();
      System.out.println("The nextInt method is used to read the number ");
      System.out.println("The number is: ");
      System.out.println(value);
   }
}

Output

Required packages have been imported
Variable to store value is defined
A reader object has been defined

Enter a number: 55
The nextInt method is used to read the number
The number is:
55

Example 2

Here, the input is being entered by the user based on a prompt and read through 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());
      System.out.println("The number is : "+number);
   }
}

Output

An object of InputStreamReader class is created
A constructor of the BufferedReader class is created
Enter a number:
The number is : 45
raja
Updated on 18-Feb-2022 12:13:10

Advertisements