我们如何在 Java 中从标准输入读取内容?
在 Java 中,标准输入 (stdin) 可表示为 System.in。System.in 是 InputStream 类 的一个实例。这意味着它的所有方法都作用于字节,而不是 String。要从键盘读取任何数据,我们可以使用 Reader 类 或 Scanner 类。
示例 1
import java.io.*; public class ReadDataFromInput { public static void main (String[] args) { int firstNum, secondNum, result; BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 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
示例 2
import java.util.*; public class ReadDataFromScanner { public static void main (String[] args) { int firstNum, secondNum, result; Scanner scanner = new Scanner(System.in); 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
广告