標準輸入(stdin)在Java中可以用System.in來表示。 System.in 是InputStream 類別的一個實例。這意味著它的所有方法都適用於字節,而不是字串。要從鍵盤讀取任何數據,我們可以使用 Reader 類別或 Scanner 類別。
import java.io.*; public class ReadDataFromInput { public static void main (String[] args) { int firstNum, secondNum, result; <strong> BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); </strong> try { System.out.println("Enter a first number:"); firstNum = Integer.parseInt(br.readLine()); System.out.println("Enter a second number:"); secondNum = Integer.parseInt(br.readLine()); result = firstNum * secondNum; System.out.println("The Result is: " + result); } catch (IOException ioe) { System.out.println(ioe); } } }
Enter a first number: 15 Enter a second number: 20 The Result is: 300
import java.util.*; public class ReadDataFromScanner { public static void main (String[] args) { int firstNum, secondNum, result; <strong> Scanner scanner = new Scanner(System.in); </strong> System.out.println("Enter a first number:"); firstNum = Integer.parseInt(scanner.nextLine()); System.out.println("Enter a second number:"); secondNum = Integer.parseInt(scanner.nextLine()); result = firstNum * secondNum; System.out.println("The Result is: " + result); } }
Enter a first number: 20 Enter a second number: 25 The Result is: 500
以上是在Java中,我們如何從標準輸入讀取資料?的詳細內容。更多資訊請關注PHP中文網其他相關文章!