题解 | #简单计算器#
简单计算器
http://www.nowcoder.com/practice/b8f770674ba7468bb0a0efcc2aa3a239
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
while(scan.hasNextLine()) {
String str = scan.nextLine();
String[] strs = str.split("[+\\-*/]");//通过+-*/进行字符的分割
if(strs.length < 2) {//如果没有正确的运算符或者无输入,则字符串无法分隔为两部分
System.out.println("Invalid operation!");
} else {//分割成功,即输入格式正确
double num1 = Double.parseDouble(strs[0]);
double num2 = Double.parseDouble(strs[1]);
String operate = str.substring(strs[0].length(),strs[0].length() + 1);
switch(operate) {
case "+":
System.out.printf("%.4f+%.4f=%.4f\n", num1, num2, num1 + num2);
break;
case "-":
System.out.printf("%.4f-%.4f=%.4f\n", num1, num2, num1 - num2);
break;
case "*":
System.out.printf("%.4f*%.4f=%.4f\n", num1, num2, num1 * num2);
break;
case "/":
if(num2 != 0.0) {
System.out.printf("%.4f/%.4f=%.4f\n", num1, num2, num1 / num2);
} else {
System.out.println("Wrong!Division by zero!");
}
break;
}
}
}
}
}