解析一个只包含加减运算符的算式
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);
}
}
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);
}
}
相关文章推荐
- 未能在当前目标框架中解析主引用“System.Net.Http”,它是一个框架程序集。“.NETFramework,Version=v4.0”。若要解决此问题,请移除引用“System.Net.Http”,或将应用程序的目标重新指向包含“System.Net.Http”的框架版本。 Zephyr.Web
- Json文档中有多个属性,其中一个属性包含一个数组的解析
- 解析带运算符字符串的一个小算法
- 设计一个日期类Date,,要求: (1)包含年(year)、月(month)和日(day)私有数据成员。 (2)包含构造函数,重载关于一日期加上天数的加法运算符+、重载关于一日期减去天数的减加运算符-
- 构造包含一个元素的元组规则解析
- location的search操作——解析url字符串,返回包含所有参数的一个对象
- 建立一个二维坐标系的类TwoCoor,用x、y表示坐标值,实现两坐标点的加减运算,计算两坐标点之间的距离,并重载输入输出运算符,使之能够直接输入输出坐标点的坐标值。
- WCF一个小经验分享一下(元数据包含无法解析的引用)
- 解析带运算符字符串的一个小算法
- 字符串的四则运算。给出一个字符串,包含0~9的数字和+-*/()的运算符,-仅代表减号不代表负数。
- 设计一个日期类Date,,要求: (1)包含年(year)、月(month)和日(day)私有数据成员。 (2)包含构造函数,重载关于一日期加上天数的加法运算符+、重载关于一日期减去天数的减加运算符-
- 使用递归解析给定的任意一个xml文档并且将其内容输出到命令行上
- 检查一个字符串中是否包含另一个字符的函数
- C# winfrom中在一个主窗口包含子窗口
- 构造一个单词查找树,支持以下两个操作的数据结构: 添加和搜索,只包含字母a-z或.。
- 一个整数转化为二进制数后包含1的个数
- 作用域解析运算符
- 对一个存储学生信息的单向链表,按照学号升序对链表进行排序,每个节点包含了一个学生ID
- 如何设计一个 iOS 控件?(iOS 控件完全解析)
- 第3课:在IDE下开发一个Scala程序,透彻解析及Scala控制结构