Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để đọc số từ đầu vào chuẩn

Trong bài này, chúng ta sẽ hiểu cách đọc một số từ đầu vào chuẩn trong Java. Phương thức Scanner.nextInt () được sử dụng để đọc số. Phương thức java.util.Scanner.nextInt () Quét mã thông báo tiếp theo của đầu vào dưới dạng int. Lệnh gọi phương thức này có dạng nextInt () hoạt động giống hệt như lệnh gọi nextInt (cơ số), trong đó cơ số là cơ số mặc định của máy quét này.

Dưới đây là một minh chứng về điều tương tự -

Đầu vào

Giả sử đầu vào của chúng tôi là -

55

Đầu ra

Đầu ra mong muốn sẽ là -

The input value is 55

Thuật toán

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

Ví dụ 1

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java để đọc số từ đầu vào chuẩn .

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);
   }
}

Đầu ra

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

Ví dụ 2

Tại đây, đầu vào đang được người dùng nhập dựa trên lời nhắc và đọc thông qua đối tượng InputStreamReader.

Ở đây, đầu vào đang được người dùng nhập dựa trên lời nhắc. Bạn có thể thử trực tiếp ví dụ này trong công cụ nền tảng mã hóa của chúng tôi Chương trình Java để đọc số từ đầu vào chuẩn .

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);
   }
}

Đầu ra

An object of InputStreamReader class is created
A constructor of the BufferedReader class is created
Enter a number:
The number is : 45