试试这个:
import java.util.Scanner;
public class SimpleCalculatorScanner {
public static void main(final String[] args) {
Scanner sc = new Scanner(System.in);
String[] variables = sc.nextLine().split(" ");
int a = 0;
int b = 0;
int c = 0;
int d = 0;
for(int i = 0; i < variables.length; i++) {
try {
if(variables[i].substring(0, 2).equals("a=")) {
a=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals("b=")) {
b=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals("c=")) {
c=Integer.parseInt(variables[i].substring(2));
}else if(variables[i].substring(0, 2).equals("d=")){
d=Integer.parseInt(variables[i].substring(2));
}else {
System.out.println("Unrecognized variable "+variables[i].substring(0, 1)+" detected");
return;
}
}catch(NumberFormatException e) {
System.out.println("The character you assigned to variable "+variables[i].substring(0, 1)+" isn't a number");
return;
} }
if (a < b){
System.out.printf("%d", a * c);
}
if (a == b){
System.out.printf("%d", a * c);
}
if (a > b){
System.out.printf("%d", a * d);
}
}
}
示例 I/O
输入
b=5 d=10 a=10 c=4
输出
100
输入 2
b=5 d=10 e=10 c=4
输出 2
Unrecognized variable e detected
输入 3
a=10 b=5 c=4 d=iforgot
输出 3
The character you assigned to variable d isn't a number
工作原理
Scanner 读取一个新行,然后通过拆分每个空格将其转换为一个数组。
一旦变量被存储到一个数组中,我们运行一个for循环来测试数组中每一项的前2个字符是否是a=、b=、c=或d=。如果是a=,则将数组中item的=后面的每个字符解析为整数,赋值给变量a,反之亦然。
如果它不能识别变量,它将打印Unrecognized variable <variablename> detected。
如果分配给变量的字符不是数字,它将打印The character you assigned to variable <variablename> isn't a number