用java写的计算器的程序,主要是通过控制台输入,主要方法是使用scanner类来接收用户从键盘输入的一个算式,通过分解算式,存入两个字符串,判断中间的的符号,进行相应计算,如下代码:
System.out.println("-----------------------------------");
Scanner?in?=?new?Scanner(System.in);//接收用户从键盘输入的字符
String?str?=?in.nextLine();
StringBuffer?buffer?=?new?StringBuffer();//保存左侧的数字
StringBuffer?buffer1?=?new?StringBuffer();//保存右侧的数字
char?t?=?'?';//保存运算符
for?(int?i?=?0;?i?str.length();?i++)?{
if?(str.charAt(i)?==?'+'?||?str.charAt(i)?==?'-'
||?str.charAt(i)?==?'*'?||?str.charAt(i)?==?'/')?{
t?=?str.charAt(i);//识别是什么运算符
for?(int?j?=?i?+?1;?j?str.length();?j++)?{
buffer1.append(str.charAt(j));
}
break;
}?else?{
buffer.append(str.charAt(i));
String?c?=?buffer.toString();
String?d?=?buffer1.toString();
double?a?=?Double.parseDouble(c);
double?b?=?Double.parseDouble(d);
double?sum?=?0;
if?(t?==?'+')?{
sum?=?a?+?b;
if?(t?==?'-')?{
sum?=?a?-?b;
if?(t?==?'*')?{
sum?=?a?*?b;
if?(t?==?'/')?{
sum?=?a?/?b;
System.out.println("程序运算...");
System.out.println(c+t+d+"="+sum);
System.out.print("-----------------------------------");
运行结果如下:
代码网上很多,只说说算法吧
把这样的表达式拆成:(操作数)(操作符) 、
(术语叫做逆波兰式)
默认的计算顺序是从左往右,记为left.另设从右往左,记为right
设计Element类,具有 操作数 operant, 操作符operator, 操作顺序 order三个属性
用两个先进后出的栈结构StackElement a,b;
一开始所有的Element都在a中,逐个弹出计算合并值,
当遇到乘、除、括号时计算顺序改变成right,把当前结果放到b中暂存.
直到再次遇到加、减、)右括号时,意味计算顺序复位成left,先把b中的暂存结果全部合并后,再继续算a中的剩余数据
最后合并成一个结果值.
表达式求值 逆波兰表达式算法 如下:
import java.util.ArrayList;
import java.util.List;
public class MyStack {
private ListString l;
private int size;
public String top;
public MyStack() {
l = new ArrayListString();
size = 0;
top = null;
public int size() {
return size;
public void push(String s) {
l.add(s);
top = s;
size++;
public String pop() {
String s = l.get(size - 1);
l.remove(size - 1);
size--;
top = size == 0 ? null : l.get(size - 1);
return s;
public class Nbl {
private static MyStack ms1 = new MyStack();//生成逆波兰表达式的栈
/**
* 将字符串转换为中序表达式
*/
public static ListString zb(String s) {
ListString ls = new ArrayListString();//存储中序表达式
int i = 0;
String str;
char c;
do {
ls.add("" + c);
i++;
} else {
str = "";
str += c;
ls.add(str);
} while (i s.length());
return ls;
* 将中序表达式转换为逆波兰表达式
public static ListString parse(ListString ls) {
ListString lss = new ArrayListString();
for (String ss : ls) {
if (ss.matches("\d+")) {
lss.add(ss);
} else if (ss.equals("(")) {
ms1.push(ss);
} else if (ss.equals(")")) {
while (!ms1.top.equals("(")) {
lss.add(ms1.pop());
ms1.pop();
while (ms1.size() != 0 getValue(ms1.top) = getValue(ss)) {
while (ms1.size() != 0) {
return lss;
* 对逆波兰表达式进行求值
public static int jisuan(ListString ls) {
for (String s : ls) {
if (s.matches("\d+")) {
if (s.equals("+")) {
a = a + b;
} else if (s.equals("-")) {
a = a - b;
} else if (s.equals("*")) {
a = a * b;
} else if (s.equals("\")) {
a = a / b;
* 获取运算符优先级
public static int getValue(String s) {
return 1;
return 0;
public static void main(String[] args) {
while(Character.isDigit(chars[i])||chars[i]=='.') {
s.append(chars[i]);
这一段是死循环..stack一直追加参数,所以溢出了
import java.util.Stack;
* @author wengsh
public class MyDemo {
public static void main(String[] a) {
StackCharacter stack = new StackCharacter();
StringBuffer sb = new StringBuffer();
if (a.length 1) {
System.out.println("参数长度不够");
String s = a[0].trim();
char[] c = s.toCharArray();
try {
for (int i = 0; i c.length; i++) {
int priority = getPriority(c[i]);
if (priority == -1) { // 如果是数字
sb.append(c[i]); // 输出数字或都字母
if (stack.isEmpty()) {// 当栈为空时
stack.push(c[i]); // 把字符压入栈
} else {// 当栈为不空时
while (!stack.isEmpty()
sb.append(stack.pop());// 把'('之上的字符弹出栈并输出
stack.pop(); // 栈弹出'('
// 当要压入栈的字符的优先级小于 等于栈顶字符的优先级且栈顶字符不为'('时
priority = getPriority(stack.peek())
sb.append(stack.pop()); // 弹出栈顶字符并输出
stack.push(c[i]);// 将此时的字符压入栈顶
// 读到输入末尾
while (!stack.isEmpty()) {
sb.append(stack.pop()); // 弹出栈中所有元素并输出
System.out.println(calstack(sb.toString()));//结果 110.0
} catch (Exception e) {
e.printStackTrace();
* 获得字符串优先级如果字符不在给定的范围内,则抛出异常,数字和字母的优先级最低
*
* @param c
* @return
* @throws Exception
public static int getPriority(char c) throws Exception {
int priority = -1;
if (Character.isDigit(c)) {
priority = -1;
} else if (Character.isLetter(c)) {
priority = 0;
if (c == '(') {
} else if (c == '*' || c == '/') {
} else if (c == '+' || c == '-') {
} else if (c == ')') {
throw new Exception("无法解析的前序表达式: " + c);
return priority;
* 计算栈结果
* @param s
public static float calstack(String s) {
StackFloat stack = new StackFloat();
if (priority == -1) {
stack.push(new Float(Character.digit(c[i], 10)));
stack.push(cal(stack.pop(), stack.pop(), c[i]));
return stack.pop();
* a b 运算
* @param a
* @param b
* @param opertor
public static float cal(float a, float b, char opertor) {
float r = 0;
switch (opertor) {
case '+':
r = a + b;
case '-':
r = a - b;
case '*':
r = a * b;
case '/':
r = a / b;
return r;
下面的代码是用来计算表达式的,看看是不是你要的
public class OPNode {
char op;// 运算符号
int level;// 优先级
//设置优先级
public OPNode(String op) {
this.op = op.charAt(0);
if (op.equals("+") || op.equals("-")) {
this.level = 1;
} else if (op.equals("*") || op.equals("/")) {
} else if (op.equals("(")) {
this.level = -1;
//主类
import java.util.Deque;
import java.util.LinkedList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class OPText {
List list = new LinkedList();
//正则式
Pattern entryOfExpression = Pattern
Deque stack = new LinkedList();//栈
Matcher m = entryOfExpression.matcher(expression);
while (m.find()) {
//提取语素
String nodeString = expression.substring(m.start(), m.end());
list.add(Double.valueOf(nodeString));//如果是数字直接送入列表
OPNode opn = new OPNode(nodeString);//如果是运算符
int peekLevel = (stack.peek() == null) ? 0 : ((OPNode) stack
.peek()).level;
if (opn.level =peekLevel) {
stack.push(opn);//新的运算符比旧的优先级别高则入栈
if (opn.level == -1) {
OPNode temp = (OPNode) stack.pop();
list.add(temp);
System.out.println(nodeString);
temp = (OPNode) stack.pop();
stack.push(opn);
} else {//如果新运算符比栈顶运算符底则一直出栈
while (temp.level opn.level) {
if (stack.isEmpty()) {
OPNode temp = null;
}//后续表达式计算
stack.clear();
for (Object o : list) {
if (o instanceof Double) {
stack.push(o);//为数字入栈
double op1 = ((Double) stack.pop()).doubleValue();
switch (((OPNode) o).op) {
System.out.println("结果为:" + stack.pop());
呃,太晚了,没心思去改了
明天再说
以上就是土嘎嘎小编为大家整理的逆波兰java代码相关主题介绍,如果您觉得小编更新的文章只要能对粉丝们有用,就是我们最大的鼓励和动力,不要忘记讲本站分享给您身边的朋友哦!!