常规的表达式求值,我们都会根据计算的优先级来计算。比如/的优先级就高于+-。但是小易所生活的世界的表达式规则很简单,从左往右依次计算即可,而且小易所在的世界没有除法,意味着表达式中没有/,只有(+, - 和 )。现在给出一个表达式,需要你帮忙计算出小易所在的世界这个表达式的值为多少
输入描述:
输入为一行字符串,即一个表达式。其中运算符只有-,+,*。参与计算的数字只有0~9.
保证表达式都是合法的,排列规则如样例所示。
输出描述:
输出一个数,即表达式的值
输入例子1:
3+5*7
输出例子1:
56
解题思路
拆分字符串。
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
if (str == null || str.length() == 0) {
System.out.println(0);
return;
}
int index = 0;
while (str.charAt(index) != '+' && str.charAt(index) != '-' && str.charAt(index) != '*') {
index++;
}
long result = Integer.valueOf(str.substring(0, index));
while (index < str.length()) {
char operator = str.charAt(index);
int start = ++index;
while (index < str.length() && str.charAt(index) != '+' && str.charAt(index) != '-'
&& str.charAt(index) != '*') {
index++;
}
int num = Integer.valueOf(str.substring(start, index));
switch (operator) {
case '+':
result += num;
break;
case '-':
result -= num;
break;
case '*':
result *= num;
break;
}
}
System.out.println(result);
}
}
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
String[] nums = str.split("\\+|-|\\*");
int count = 0, index = 0;
long result = Integer.valueOf(nums[0]);
while (count < nums.length - 1) {
while (str.charAt(index) != '+' && str.charAt(index) != '-' && str.charAt(index) != '*') {
index++;
}
char operator = str.charAt(index);
switch (operator) {
case '+':
result += Integer.valueOf(nums[count + 1]);
break;
case '-':
result -= Integer.valueOf(nums[count + 1]);
break;
case '*':
result *= Integer.valueOf(nums[count + 1]);
break;
}
count++;
index++;
}
System.out.println(result);
}
}