package huawei;
import java.util.Scanner;
/**
* 通过键盘输入100以内正整数的加、减运算式,请编写一个程序输出运算结果字符串。
输入字符串的格式为:“操作数1 运算符 操作数2”,“操作数”与“运算符”之间以一个空格隔开。
补充说明:
1、操作数为正整数,不需要考虑计算结果溢出的情况。
2、若输入算式格式错误,输出结果为“0”。
示例
输入:“4 + 7” 输出:“11”
输入:“4 - 7” 输出:“-3”
输入:“9 ++ 7” 输出:“0” 注:格式错误
关键:将字符串转换为整数,通过包装类实现
* @author USER
*
*/
public class MathCompution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
String string = in.nextLine();
int result = arithmetic(string);
System.out.println(result);
}
private static int arithmetic(String string) {
// TODO Auto-generated method stub
String[] str = string.split(" ");
int a = Integer.parseInt(str[0]);
int b = Integer.parseInt(str[2]);
switch (str[1]) {
case "+":
return a+b;
case "-":
return a-b;
default:
return 0;
}
}
}
华为机试---简单的加减运算
最新推荐文章于 2020-04-05 18:20:05 发布