Java程式讀取標準輸入中的數字
在本文中,我們將瞭解如何在 Java 中從標準輸入讀取數字。 Scanner.nextInt() 方法 來自 java.util 包 用於讀取數字。java.util.Scanner.nextInt() 方法將輸入的下一個標記掃描為 int 型別。此方法的呼叫形式 nextInt() 的行為與呼叫 nextInt(radix) 完全相同,其中 radix 是此掃描程式的預設基數。
問題陳述
編寫一個 Java 程式,從標準輸入讀取數字。以下是演示 -
輸入
55
輸出
The input value is 55
不同的方法
以下是從標準輸入讀取數字的兩種方法 -
使用 Scanner 類
以下是使用 Scanner 類從標準輸入讀取數字的步驟 -
- 從java.util 包匯入必要的類
- 建立一個名為PrintNumber的類。
- 宣告一個整數變數來儲存輸入值。
- 例項化Scanner 類以讀取使用者的輸入。
- 顯示一條訊息,提示使用者輸入一個數字。
- 使用Scanner 類的nextInt() 方法讀取整數輸入。
- 將輸入的數字列印到控制檯。
示例
這裡,輸入是由使用者根據提示輸入的 -
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);
}
}
輸出
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
使用 BufferedReader 類
以下是使用 BufferedReader 類從標準輸入讀取數字的步驟 -
- 匯入必要的類 import java.io 包。
- 建立一個名為readNum的類。
- 建立一個InputStreamReader 物件,它讀取位元組並將其解碼為字元。
- 之後將建立一個BufferedReader 物件,它包裝 InputStreamReader 以緩衝輸入以實現高效讀取。
- 提示使用者輸入。
- 我們將使用 BufferedReader 的readLine()讀取輸入,並使用Integer.parseInt()將其轉換為整數。
- 將輸入的數字列印到控制檯。
示例
這裡,輸入是由使用者根據提示輸入的,並透過 InputStreamReader 物件讀取 -
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);
}
}
輸出
An object of InputStreamReader class is created A constructor of the BufferedReader class is created Enter a number: The number is : 45
廣告
資料結構
網路
關係型資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP