要从标准输入读取数字,必须将其读取为字符串并将其解析为数字。java.util
包中的Scanner
类根据模式读取并解析基本类型和字符串中的文本。文本源可以是InputStream
,文件,String
对象或可读对象。
可以使用Scanner
对象从标准输入System.in
中读取原始类型值。以下代码说明了如何使用Scanner
类构建一个小型计算器来执行加,减,乘和除。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
mport java.util.Scanner; public class Calculator { public static void main(String[] args) { System.out.println( "type something like: 1+3" ); Scanner scanner = new Scanner(System.in); double n1 = Double.NaN; double n2 = Double.NaN; String operation = null ; try { n1 = scanner.nextDouble(); operation = scanner.next(); n2 = scanner.nextDouble(); double result = calculate(n1, n2, operation); System.out.printf( "%s %s %s = %.2f%n" , n1, operation, n2, result); } catch (Exception e) { System.out.println( "An invalid expression." ); } } public static double calculate( double op1, double op2, String operation) { switch (operation) { case "+" : return op1 + op2; case "-" : return op1 - op2; case "*" : return op1 * op2; case "/" : return op1 / op2; } return Double.NaN; } } |