在Java中,我们如何从标准输入读取数据?
标准输入(stdin)在Java中可以用System.in来表示。 System.in 是InputStream 类的一个实例。这意味着它的所有方法都适用于字节,而不是字符串。要从键盘读取任何数据,我们可以使用 Reader 类或 Scanner 类。
示例1
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
示例2
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中,我们如何从标准输入读取数据?的详细内容,更多请关注其它相关文章!