就是把昨天写的写成了爪哇,少了一些功能,基本的在,牛逼的大牛可以拿去修改做的更好。
public boolean judge(char ch)//判断是不是字符数字
{
if(ch >= '0' && ch <= '9')
{
return true;
}
return false;
}
public String[] tochange(String s_1)//中缀表达式转换为后缀表达式
{
String S[] = new String[1000];
StringBuffer numBuffer = new StringBuffer();
Stack<String> s = new Stack<String>();
int i = 0, j = 0;
char ch;
while(i != s_1.length())
{
ch = s_1.charAt(i);
if(ch >= '0' && ch <= '9')
{
while (judge(ch))
{
numBuffer.append(ch);
ch = s_1.charAt(++i);
}
S[j++] = numBuffer.toString();
numBuffer = new StringBuffer();
continue;
}
else if(ch == '(')
{
s.push("(");
}
else if(ch == ')')
{
while(s.peek() != "(")
{
S[j++] = s.pop();
}
s.pop();
}
else if(ch == '+' || ch == '-')
{
while(s.size() != 0 && s.peek() != "(")
{
S[j++] = s.pop();
}
s.push(String.valueOf(ch));
}
else if(ch == '*' || ch == '/')
{
while(s.size() != 0 && (s.peek()== "*" || s.peek() == "/"))
{
S[j++] = s.pop();
}
s.push(String.valueOf(ch));
}
i++;
}
while (s.size() != 0)
S[j++] = s.pop();
S[j] = "=";
return S;
}
public int add(String s_1)//进行计算
{
String []sn = tochange(s_1);
Stack<String>s = new Stack<String>();
int i = 0,n = 0,m = 0,x = 0;
char ch;
while(sn[i] != "=")
{
ch = sn[i].charAt(0);
if(ch >= '0' && ch <= '9')
{
s.push(String.valueOf(sn[i]));
}
else if(ch == '+')
{
n = Integer.parseInt(s.pop());
m = Integer.parseInt(s.pop());
x = n + m;
s.push(String.valueOf(x));
}
else if(ch == '-')
{
n = Integer.parseInt(s.pop());
m = Integer.parseInt(s.pop());
x = m - n;
s.push(String.valueOf(x));
}
else if(ch == '*')
{
n = Integer.parseInt(s.pop());
m = Integer.parseInt(s.pop());
x = m * n;
s.push(String.valueOf(x));
}
else if(ch == '/')
{
n = Integer.parseInt(s.pop());
m = Integer.parseInt(s.pop());
x = m / n;
s.push(String.valueOf(x));
}
i++;
}
String ss = s.pop();
int number = Integer.parseInt(ss);
return number;
}