您的位置:首页 > 其它

解析一个只包含加减运算符的算式

2009-01-06 12:12 162 查看
package p1231;

public class Question3 {
public static void main(String[] args) {
String str = "5-5+1-6+7-4-2=";
char charArray[] = str.toCharArray();
int result = 0;
int temp = 0;
boolean digit = false;
boolean first = true;
char oprator = ' ';
for (int i = 0; i < charArray.length; i++) {
if (Character.isDigit(charArray[i])) {
if (digit == false) {
temp = charArray[i] - '0';
digit = true;
} else {
temp *= 10;
temp += charArray[i] - '0';
}
} else {
digit = false;
if (first == true) {
result = temp;
first = false;
}
if (oprator == '+') {
result += temp;
}
if (oprator == '-') {
result -= temp;
}
if (oprator == '=') {
break;
}
oprator = charArray[i];
}
}

System.out.println(result);

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐