import java.util.Stack; public class Calcu{ Stack <Integer>num; Stack <String>exp; String expression="7+(8+2*2)/3-1="; public Calcu(){ num=new Stack<Integer>(); exp=new Stack<String>(); } public void calculate(){ char t; int s; int len=expression.length(); for(int i=0;i<len;i++){ t=expression.charAt(i); switch(t){ case '-': case '+':if(!exp.empty()&& !exp.peek().equals("(") && !exp.peek().equals(")")){ s=compute(exp.pop()); num.push(s); } exp.push(String.valueOf(t)); break; case '/': case '*': if(!exp.empty()&& exp.peek().equals("/")){ compute(exp.pop()); }else if(!exp.empty() && exp.peek().equals("*")){compute(exp.pop());} else exp.push(String.valueOf(t));break; case '(':exp.push(String.valueOf(t));break; case ')':{ while(!exp.peek().equals("(")){ s=compute(exp.pop()); num.push(s); } exp.pop(); break; } case '=':{ while(!exp.empty()){ s=compute(exp.pop()); num.push(s); } System.out.println(num.pop()); break; } default:num.push(t-48); } } } private int compute(String exp){ int n2=num.pop(); int n1=num.pop(); switch(exp.charAt(0)){ case '+':return n1+n2; case '-':return n1-n2; case '*':return n1*n2; case '/':return n1/n2; } return -1; } public static void main(String args[]){ Calcu c=new Calcu(); c.calculate(); } }
上面的代码有点小问题。。 import java.util.Stack; public class Calcu{ Stack <Integer>num; Stack <String>exp; String expression="7+(8+2*2)/3-1="; public Calcu(){ num=new Stack<Integer>(); exp=new Stack<String>(); } public void calculate(){ char t; int s; int len=expression.length(); for(int i=0;i<len;i++){ t=expression.charAt(i); switch(t){ case '-': case '+':if(!exp.empty()&& !exp.peek().equals("(") && !exp.peek().equals(")")){ s=compute(exp.pop()); num.push(s); } exp.push(String.valueOf(t)); break; case '/': case '*': if(!exp.empty()&& exp.peek().equals("/")){ s=compute(exp.pop()); num.push(s); }else if(!exp.empty() && exp.peek().equals("*")){ s=compute(exp.pop()); num.push(s); } exp.push(String.valueOf(t));break; case '(':exp.push(String.valueOf(t));break; case ')':{ while(!exp.peek().equals("(")){ s=compute(exp.pop()); num.push(s); } exp.pop(); break; } case '=':{ while(!exp.empty()){ s=compute(exp.pop()); num.push(s); } System.out.println(num.pop()); break; } default:num.push(t-48); } } } private int compute(String exp){ int n2=num.pop(); int n1=num.pop(); switch(exp.charAt(0)){ case '+':return n1+n2; case '-':return n1-n2; case '*':return n1*n2; case '/':return n1/n2; } return -1; } public static void main(String args[]){ Calcu c=new Calcu(); c.calculate(); } }
给你逆波兰式算法.经过测试 package expression;
import java.io.*; import java.util.*;
public class Expression { private ArrayList expression = new ArrayList();// 存储中序表达式
private ArrayList right = new ArrayList();// 存储右序表达式
private String result;// 结果
// 依据输入信息创建对象,将数值与操作符放入ArrayList中 private Expression(String input) { StringTokenizer st = new StringTokenizer(input, "+-*/()", true); while (st.hasMoreElements()) { expression.add(st.nextToken()); } }
// 将中序表达式转换为右序表达式 private void toRight() { Stacks aStack = new Stacks(); String operator; int position = 0; while (true) { if (Calculate.isOperator((String) expression.get(position))) { if (aStack.top == -1 || ((String) expression.get(position)).equals("(")) { aStack.push(expression.get(position)); } else { if (((String) expression.get(position)).equals(")")) { if (!((String) aStack.top()).equals("(")) { operator = (String) aStack.pop(); right.add(operator); } } else { if (Calculate.priority((String) expression .get(position)) <= Calculate .priority((String) aStack.top()) && aStack.top != -1) { operator = (String) aStack.pop(); if (!operator.equals("(")) right.add(operator); } aStack.push(expression.get(position)); } } } else right.add(expression.get(position)); position++; if (position >= expression.size()) break; } while (aStack.top != -1) { operator = (String) aStack.pop(); right.add(operator); } }
// 对右序表达式进行求值 private void getResult() { this.toRight(); Stacks aStack = new Stacks(); String op1, op2, is = null; Iterator it = right.iterator();
while (it.hasNext()) { is = (String) it.next(); if (Calculate.isOperator(is)) { op1 = (String) aStack.pop(); op2 = (String) aStack.pop(); aStack.push(Calculate.twoResult(is, op1, op2)); } else aStack.push(is); } result = (String) aStack.pop(); it = expression.iterator(); while (it.hasNext()) { System.out.print((String) it.next()); } System.out.println("=" + result); }
public static void main(String avg[]) { try { System.out.println("Input a expression:"); BufferedReader is = new BufferedReader(new InputStreamReader( System.in)); for (;;) { String input = new String(); input = is.readLine().trim(); if (input.equals("q")) break; else { Expression boya = new Expression(input); boya.getResult(); } System.out .println("Input another expression or input 'q' to quit:"); } is.close(); } catch (IOException e) { System.out.println("Wrong input!!!"); } } } java 代码 package expression;
public class Calculate { // 判断是否为操作符号 public static boolean isOperator(String operator) { if (operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("(") || operator.equals(")")) return true; else return false; }
// 设置操作符号的优先级别 public static int priority(String operator) { if (operator.equals("+") || operator.equals("-") || operator.equals("(")) return 1; else if (operator.equals("*") || operator.equals("/")) return 2; else return 0; }
// 做2值之间的计算 public static String twoResult(String operator, String a, String b) { try { String op = operator; String rs = new String(); double x = Double.parseDouble(b); double y = Double.parseDouble(a); double z = 0; if (op.equals("+")) z = x + y; else if (op.equals("-")) z = x - y; else if (op.equals("*")) z = x * y; else if (op.equals("/")) z = x / y; else z = 0; return rs + z; } catch (NumberFormatException e) { System.out.println("input has something wrong!"); return "Error"; } } } java 代码 package expression; import java.util.*; //栈类 public class Stacks{ private LinkedList list=new LinkedList(); int top=-1; public void push(Object value){ top++; list.addFirst(value); } public Object pop(){ Object temp=list.getFirst(); top--; list.removeFirst(); return temp;
} public Object top(){ return list.getFirst(); } }
package expression;
import java.io.*; import java.util.*;
public class Expression { private ArrayList expression = new ArrayList();// 存储中序表达式
private ArrayList right = new ArrayList();// 存储右序表达式
private String result;// 结果
// 依据输入信息创建对象,将数值与操作符放入ArrayList中 private Expression(String input) { StringTokenizer st = new StringTokenizer(input, "+-*/()", true); while (st.hasMoreElements()) { expression.add(st.nextToken()); } }
// 将中序表达式转换为右序表达式 private void toRight() { Stacks aStack = new Stacks(); String operator; int position = 0; while (true) { if (Calculate.isOperator((String) expression.get(position))) { if (aStack.top == -1 || ((String) expression.get(position)).equals("(")) { aStack.push(expression.get(position)); } else { if (((String) expression.get(position)).equals(")")) { if (!((String) aStack.top()).equals("(")) { operator = (String) aStack.pop(); right.add(operator); } } else { if (Calculate.priority((String) expression .get(position)) <= Calculate .priority((String) aStack.top()) && aStack.top != -1) { operator = (String) aStack.pop(); if (!operator.equals("(")) right.add(operator); } aStack.push(expression.get(position)); } } } else right.add(expression.get(position)); position++; if (position >= expression.size()) break; } while (aStack.top != -1) { operator = (String) aStack.pop(); right.add(operator); } }
// 对右序表达式进行求值 private void getResult() { this.toRight(); Stacks aStack = new Stacks(); String op1, op2, is = null; Iterator it = right.iterator();
while (it.hasNext()) { is = (String) it.next(); if (Calculate.isOperator(is)) { op1 = (String) aStack.pop(); op2 = (String) aStack.pop(); aStack.push(Calculate.twoResult(is, op1, op2)); } else aStack.push(is); } result = (String) aStack.pop(); it = expression.iterator(); while (it.hasNext()) { System.out.print((String) it.next()); } System.out.println("=" + result); }
public static void main(String avg[]) { try { System.out.println("Input a expression:"); BufferedReader is = new BufferedReader(new InputStreamReader( System.in)); for (;;) { String input = new String(); input = is.readLine().trim(); if (input.equals("q")) break; else { Expression boya = new Expression(input); boya.getResult(); } System.out .println("Input another expression or input 'q' to quit:"); } is.close(); } catch (IOException e) { System.out.println("Wrong input!!!"); } } } java 代码 package expression;
public class Calculate { // 判断是否为操作符号 public static boolean isOperator(String operator) { if (operator.equals("+") || operator.equals("-") || operator.equals("*") || operator.equals("/") || operator.equals("(") || operator.equals(")")) return true; else return false; }
// 设置操作符号的优先级别 public static int priority(String operator) { if (operator.equals("+") || operator.equals("-") || operator.equals("(")) return 1; else if (operator.equals("*") || operator.equals("/")) return 2; else return 0; }
// 做2值之间的计算 public static String twoResult(String operator, String a, String b) { try { String op = operator; String rs = new String(); double x = Double.parseDouble(b); double y = Double.parseDouble(a); double z = 0; if (op.equals("+")) z = x + y; else if (op.equals("-")) z = x - y; else if (op.equals("*")) z = x * y; else if (op.equals("/")) z = x / y; else z = 0; return rs + z; } catch (NumberFormatException e) { System.out.println("input has something wrong!"); return "Error"; } } } java 代码 package expression; import java.util.*; //栈类 public class Stacks{ private LinkedList list=new LinkedList(); int top=-1; public void push(Object value){ top++; list.addFirst(value); } public Object pop(){ Object temp=list.getFirst(); top--; list.removeFirst(); return temp;
} public Object top(){ return list.getFirst(); } }
public class Calcu{
Stack <Integer>num;
Stack <String>exp;
String expression="7+(8+2*2)/3-1=";
public Calcu(){
num=new Stack<Integer>();
exp=new Stack<String>();
}
public void calculate(){
char t;
int s;
int len=expression.length();
for(int i=0;i<len;i++){
t=expression.charAt(i);
switch(t){
case '-':
case '+':if(!exp.empty()&& !exp.peek().equals("(") && !exp.peek().equals(")")){
s=compute(exp.pop());
num.push(s);
} exp.push(String.valueOf(t));
break;
case '/':
case '*':
if(!exp.empty()&& exp.peek().equals("/")){
compute(exp.pop());
}else if(!exp.empty() && exp.peek().equals("*")){compute(exp.pop());}
else exp.push(String.valueOf(t));break;
case '(':exp.push(String.valueOf(t));break;
case ')':{
while(!exp.peek().equals("(")){
s=compute(exp.pop());
num.push(s);
}
exp.pop();
break;
}
case '=':{
while(!exp.empty()){
s=compute(exp.pop());
num.push(s);
}
System.out.println(num.pop());
break;
}
default:num.push(t-48);
}
}
}
private int compute(String exp){
int n2=num.pop();
int n1=num.pop();
switch(exp.charAt(0)){
case '+':return n1+n2;
case '-':return n1-n2;
case '*':return n1*n2;
case '/':return n1/n2;
}
return -1;
}
public static void main(String args[]){
Calcu c=new Calcu();
c.calculate();
}
}
import java.util.Stack;
public class Calcu{
Stack <Integer>num;
Stack <String>exp;
String expression="7+(8+2*2)/3-1=";
public Calcu(){
num=new Stack<Integer>();
exp=new Stack<String>();
}
public void calculate(){
char t;
int s;
int len=expression.length();
for(int i=0;i<len;i++){
t=expression.charAt(i);
switch(t){
case '-':
case '+':if(!exp.empty()&& !exp.peek().equals("(") && !exp.peek().equals(")")){
s=compute(exp.pop());
num.push(s);
} exp.push(String.valueOf(t));
break;
case '/':
case '*':
if(!exp.empty()&& exp.peek().equals("/")){
s=compute(exp.pop());
num.push(s);
}else if(!exp.empty() && exp.peek().equals("*")){
s=compute(exp.pop());
num.push(s);
}
exp.push(String.valueOf(t));break;
case '(':exp.push(String.valueOf(t));break;
case ')':{
while(!exp.peek().equals("(")){
s=compute(exp.pop());
num.push(s);
}
exp.pop();
break;
}
case '=':{
while(!exp.empty()){
s=compute(exp.pop());
num.push(s);
}
System.out.println(num.pop());
break;
}
default:num.push(t-48);
}
}
}
private int compute(String exp){
int n2=num.pop();
int n1=num.pop();
switch(exp.charAt(0)){
case '+':return n1+n2;
case '-':return n1-n2;
case '*':return n1*n2;
case '/':return n1/n2;
}
return -1;
}
public static void main(String args[]){
Calcu c=new Calcu();
c.calculate();
}
}
package expression;
import java.io.*;
import java.util.*;
public class Expression {
private ArrayList expression = new ArrayList();// 存储中序表达式
private ArrayList right = new ArrayList();// 存储右序表达式
private String result;// 结果
// 依据输入信息创建对象,将数值与操作符放入ArrayList中
private Expression(String input) {
StringTokenizer st = new StringTokenizer(input, "+-*/()", true);
while (st.hasMoreElements()) {
expression.add(st.nextToken());
}
}
// 将中序表达式转换为右序表达式
private void toRight() {
Stacks aStack = new Stacks();
String operator;
int position = 0;
while (true) {
if (Calculate.isOperator((String) expression.get(position))) {
if (aStack.top == -1
|| ((String) expression.get(position)).equals("(")) {
aStack.push(expression.get(position));
} else {
if (((String) expression.get(position)).equals(")")) {
if (!((String) aStack.top()).equals("(")) {
operator = (String) aStack.pop();
right.add(operator);
}
} else {
if (Calculate.priority((String) expression
.get(position)) <= Calculate
.priority((String) aStack.top())
&& aStack.top != -1) {
operator = (String) aStack.pop();
if (!operator.equals("("))
right.add(operator);
}
aStack.push(expression.get(position));
}
}
} else
right.add(expression.get(position));
position++;
if (position >= expression.size())
break;
}
while (aStack.top != -1) {
operator = (String) aStack.pop();
right.add(operator);
}
}
// 对右序表达式进行求值
private void getResult() {
this.toRight();
Stacks aStack = new Stacks();
String op1, op2, is = null;
Iterator it = right.iterator();
while (it.hasNext()) {
is = (String) it.next();
if (Calculate.isOperator(is)) {
op1 = (String) aStack.pop();
op2 = (String) aStack.pop();
aStack.push(Calculate.twoResult(is, op1, op2));
} else
aStack.push(is);
}
result = (String) aStack.pop();
it = expression.iterator();
while (it.hasNext()) {
System.out.print((String) it.next());
}
System.out.println("=" + result);
}
public static void main(String avg[]) {
try {
System.out.println("Input a expression:");
BufferedReader is = new BufferedReader(new InputStreamReader(
System.in));
for (;;) {
String input = new String();
input = is.readLine().trim();
if (input.equals("q"))
break;
else {
Expression boya = new Expression(input);
boya.getResult();
}
System.out
.println("Input another expression or input 'q' to quit:");
}
is.close();
} catch (IOException e) {
System.out.println("Wrong input!!!");
}
}
} java 代码
package expression;
public class Calculate {
// 判断是否为操作符号
public static boolean isOperator(String operator) {
if (operator.equals("+") || operator.equals("-")
|| operator.equals("*") || operator.equals("/")
|| operator.equals("(") || operator.equals(")"))
return true;
else
return false;
}
// 设置操作符号的优先级别
public static int priority(String operator) {
if (operator.equals("+") || operator.equals("-")
|| operator.equals("("))
return 1;
else if (operator.equals("*") || operator.equals("/"))
return 2;
else
return 0;
}
// 做2值之间的计算
public static String twoResult(String operator, String a, String b) {
try {
String op = operator;
String rs = new String();
double x = Double.parseDouble(b);
double y = Double.parseDouble(a);
double z = 0;
if (op.equals("+"))
z = x + y;
else if (op.equals("-"))
z = x - y;
else if (op.equals("*"))
z = x * y;
else if (op.equals("/"))
z = x / y;
else
z = 0;
return rs + z;
} catch (NumberFormatException e) {
System.out.println("input has something wrong!");
return "Error";
}
}
} java 代码
package expression;
import java.util.*;
//栈类
public class Stacks{
private LinkedList list=new LinkedList();
int top=-1;
public void push(Object value){
top++;
list.addFirst(value);
}
public Object pop(){
Object temp=list.getFirst();
top--;
list.removeFirst();
return temp;
}
public Object top(){
return list.getFirst();
}
}
package expression;
import java.io.*;
import java.util.*;
public class Expression {
private ArrayList expression = new ArrayList();// 存储中序表达式
private ArrayList right = new ArrayList();// 存储右序表达式
private String result;// 结果
// 依据输入信息创建对象,将数值与操作符放入ArrayList中
private Expression(String input) {
StringTokenizer st = new StringTokenizer(input, "+-*/()", true);
while (st.hasMoreElements()) {
expression.add(st.nextToken());
}
}
// 将中序表达式转换为右序表达式
private void toRight() {
Stacks aStack = new Stacks();
String operator;
int position = 0;
while (true) {
if (Calculate.isOperator((String) expression.get(position))) {
if (aStack.top == -1
|| ((String) expression.get(position)).equals("(")) {
aStack.push(expression.get(position));
} else {
if (((String) expression.get(position)).equals(")")) {
if (!((String) aStack.top()).equals("(")) {
operator = (String) aStack.pop();
right.add(operator);
}
} else {
if (Calculate.priority((String) expression
.get(position)) <= Calculate
.priority((String) aStack.top())
&& aStack.top != -1) {
operator = (String) aStack.pop();
if (!operator.equals("("))
right.add(operator);
}
aStack.push(expression.get(position));
}
}
} else
right.add(expression.get(position));
position++;
if (position >= expression.size())
break;
}
while (aStack.top != -1) {
operator = (String) aStack.pop();
right.add(operator);
}
}
// 对右序表达式进行求值
private void getResult() {
this.toRight();
Stacks aStack = new Stacks();
String op1, op2, is = null;
Iterator it = right.iterator();
while (it.hasNext()) {
is = (String) it.next();
if (Calculate.isOperator(is)) {
op1 = (String) aStack.pop();
op2 = (String) aStack.pop();
aStack.push(Calculate.twoResult(is, op1, op2));
} else
aStack.push(is);
}
result = (String) aStack.pop();
it = expression.iterator();
while (it.hasNext()) {
System.out.print((String) it.next());
}
System.out.println("=" + result);
}
public static void main(String avg[]) {
try {
System.out.println("Input a expression:");
BufferedReader is = new BufferedReader(new InputStreamReader(
System.in));
for (;;) {
String input = new String();
input = is.readLine().trim();
if (input.equals("q"))
break;
else {
Expression boya = new Expression(input);
boya.getResult();
}
System.out
.println("Input another expression or input 'q' to quit:");
}
is.close();
} catch (IOException e) {
System.out.println("Wrong input!!!");
}
}
} java 代码
package expression;
public class Calculate {
// 判断是否为操作符号
public static boolean isOperator(String operator) {
if (operator.equals("+") || operator.equals("-")
|| operator.equals("*") || operator.equals("/")
|| operator.equals("(") || operator.equals(")"))
return true;
else
return false;
}
// 设置操作符号的优先级别
public static int priority(String operator) {
if (operator.equals("+") || operator.equals("-")
|| operator.equals("("))
return 1;
else if (operator.equals("*") || operator.equals("/"))
return 2;
else
return 0;
}
// 做2值之间的计算
public static String twoResult(String operator, String a, String b) {
try {
String op = operator;
String rs = new String();
double x = Double.parseDouble(b);
double y = Double.parseDouble(a);
double z = 0;
if (op.equals("+"))
z = x + y;
else if (op.equals("-"))
z = x - y;
else if (op.equals("*"))
z = x * y;
else if (op.equals("/"))
z = x / y;
else
z = 0;
return rs + z;
} catch (NumberFormatException e) {
System.out.println("input has something wrong!");
return "Error";
}
}
} java 代码
package expression;
import java.util.*;
//栈类
public class Stacks{
private LinkedList list=new LinkedList();
int top=-1;
public void push(Object value){
top++;
list.addFirst(value);
}
public Object pop(){
Object temp=list.getFirst();
top--;
list.removeFirst();
return temp;
}
public Object top(){
return list.getFirst();
}
}