Java 程式獲取使用者輸入
在這篇文章中,我們將瞭解如何在 Java 中從使用者獲取輸入。這是透過使用掃描器物件實現的。 Scanner.nextInt() 方法 用於獲取輸入。java.util.Scanner.nextInt() 方法將輸入的下一個標記掃描為整數。此方法的呼叫形式為nextInt(),其行為與呼叫 nextInt(radix) 相同,其中 radix 是此掃描器的預設基數。
問題陳述
編寫一個 Java 程式來獲取使用者輸入。下面是相同的演示 -
輸入
Hello, I am John!
輸出
The input string is: Hello, I am John!
獲取使用者輸入的方法
以下是獲取使用者輸入的不同方法 -
使用 Scanner 類
以下是使用 Scanner 類在 Java 中從使用者獲取輸入的步驟 -
- 首先從 java.util 包 中匯入 Scanner 類。
- 例項化Scanner 物件以從控制檯讀取輸入。
- 通知使用者並提示輸入。
- 使用scanner.nextLine()捕獲使用者輸入的整行文字並將其儲存在名為 value 的變數中。
- 列印訊息,後跟儲存在 value 中的使用者輸入。
示例
在這裡,使用者根據提示輸入輸入。您可以在 我們的 編碼 練習工具 中即時嘗試此示例。
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);
}
}t
輸出
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!
使用 InputStreamReader 和 BufferReader
以下是使用 InputStreamReader 和 BufferReader 在 Java 中從使用者獲取輸入的步驟 -
- 從 java.io 包 中匯入所有類
- 建立InputStreamReader 物件以從控制檯讀取資料。
- 透過列印建立訊息通知使用者 InputStreamReader 物件已成功建立。
- 將 InputStreamReader 包裝在 BufferedReader 中以進行高效讀取。
- 透過列印建構函式訊息告訴使用者BufferedReader 物件現在已準備就緒。
- 提示使用者輸入。
- Integer.parseInt(in.readLine())讀取輸入作為字串,將其轉換為整數,並將其儲存在number變數中。
示例
在這裡,使用者使用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());
}
}
輸出
An object of InputStreamReader class is created A constructor of the BufferedReader class is created Enter a number: 34
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP