资讯

精准传达 • 有效沟通

从品牌网站建设到网络营销策划,从策略到执行的一站式服务

逆波兰java代码 逆波兰式代码

用Java写的计算器的程序!不需要界面!

用java写的计算器的程序,主要是通过控制台输入,主要方法是使用scanner类来接收用户从键盘输入的一个算式,通过分解算式,存入两个字符串,判断中间的的符号,进行相应计算,如下代码:

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:域名注册雅安服务器托管、营销软件、网站建设、桑日网站维护、网站推广。

System.out.println("-----------------------------------");

System.out.println("请输入一个算术表达式,如:45*23");

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("-----------------------------------");

运行结果如下:

Java计算字符串中的数学表达式的值算法怎么写?

代码网上很多,只说说算法吧

12+8/4-5+(3-4)

把这样的表达式拆成:(操作数)(操作符) 、

12+

8/

4-

5+(

3-

4)

(术语叫做逆波兰式)

默认的计算顺序是从左往右,记为left。另设从右往左,记为right

设计Element类,具有 操作数 operant, 操作符operator, 操作顺序 order三个属性

用两个先进后出的栈结构StackElement a,b;

一开始所有的Element都在a中,逐个弹出计算合并值,

当遇到乘、除、括号时计算顺序改变成right,把当前结果放到b中暂存。

直到再次遇到加、减、)右括号时,意味计算顺序复位成left,先把b中的暂存结果全部合并后,再继续算a中的剩余数据

最后合并成一个结果值。

表达式求值 逆波兰表达式算法 java版

表达式求值 逆波兰表达式算法 如下:

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;

}

}

import java.util.ArrayList;

import java.util.List;

public class Nbl {

private static MyStack ms1 = new MyStack();//生成逆波兰表达式的栈

private static MyStack ms2 = new MyStack();//运算栈

/**

* 将字符串转换为中序表达式

*/

public static ListString zb(String s) {

ListString ls = new ArrayListString();//存储中序表达式

int i = 0;

String str;

char c;

do {

if ((c = s.charAt(i)) 48 || (c = s.charAt(i)) 57) {

ls.add("" + c);

i++;

} else {

str = "";

while (i s.length() (c = s.charAt(i)) = 48

(c = s.charAt(i)) = 57) {

str += c;

i++;

}

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();

} else {

while (ms1.size() != 0 getValue(ms1.top) = getValue(ss)) {

lss.add(ms1.pop());

}

ms1.push(ss);

}

}

while (ms1.size() != 0) {

lss.add(ms1.pop());

}

return lss;

}

/**

* 对逆波兰表达式进行求值

*/

public static int jisuan(ListString ls) {

for (String s : ls) {

if (s.matches("\d+")) {

ms2.push(s);

} else {

int b = Integer.parseInt(ms2.pop());

int a = Integer.parseInt(ms2.pop());

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;

}

ms2.push("" + a);

}

}

return Integer.parseInt(ms2.pop());

}

/**

* 获取运算符优先级

* +,-为1 *,/为2 ()为0

*/

public static int getValue(String s) {

if (s.equals("+")) {

return 1;

} else if (s.equals("-")) {

return 1;

} else if (s.equals("*")) {

return 2;

} else if (s.equals("\")) {

return 2;

}

return 0;

}

public static void main(String[] args) {

System.out.println(jisuan(parse(zb("0-8+((1+2)*4)-3+(2*7-2+2)"))));

}

}

java :转变为逆波兰表示式的代码报错:堆栈溢出,怎么解决?

while(Character.isDigit(chars[i])||chars[i]=='.') {

s.append(chars[i]);

}

这一段是死循环。。stack一直追加参数,所以溢出了

java 关于逆波兰表达式的两个题

import java.util.Stack;

/**

* @author wengsh

* @date 2010-6-3 用 输入 (6+5)*(5+5) 测试一下

*/

public class MyDemo {

public static void main(String[] a) {

StackCharacter stack = new StackCharacter();

StringBuffer sb = new StringBuffer();

if (a.length 1) {

System.out.println("参数长度不够");

} else {

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]); // 输出数字或都字母

} else {

if (stack.isEmpty()) {// 当栈为空时

stack.push(c[i]); // 把字符压入栈

} else {// 当栈为不空时

if (priority == -2) { // 如果是 ')'

while (!stack.isEmpty()

getPriority(stack.peek()) != 8) {

sb.append(stack.pop());// 把'('之上的字符弹出栈并输出

}

stack.pop(); // 栈弹出'('

} else {

// 当要压入栈的字符的优先级小于 等于栈顶字符的优先级且栈顶字符不为'('时

while (!stack.isEmpty()

priority = getPriority(stack.peek())

getPriority(stack.peek()) != 8) {

sb.append(stack.pop()); // 弹出栈顶字符并输出

}

stack.push(c[i]);// 将此时的字符压入栈顶

}

}

}

}

// 读到输入末尾

while (!stack.isEmpty()) {

sb.append(stack.pop()); // 弹出栈中所有元素并输出

}

System.out.println(sb); // 结果 65+55+*

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;

} else {

if (c == '(') {

priority = 8;

} else if (c == '*' || c == '/') {

priority = 5;

} else if (c == '+' || c == '-') {

priority = 4;

} else if (c == ')') {

priority = -2;

} else {

throw new Exception("无法解析的前序表达式: " + c);

}

}

return priority;

}

/**

* 计算栈结果

* 6+5*8

* @param s

* @return

*/

public static float calstack(String s) {

StackFloat stack = new StackFloat();

char[] c = s.toCharArray();

try {

for (int i = 0; i c.length; i++) {

int priority = getPriority(c[i]);

if (priority == -1) {

stack.push(new Float(Character.digit(c[i], 10)));

} else {

stack.push(cal(stack.pop(), stack.pop(), c[i]));

}

}

} catch (Exception e) {

e.printStackTrace();

}

return stack.pop();

}

/**

* a b 运算

* @param a

* @param b

* @param opertor

* @return

*/

public static float cal(float a, float b, char opertor) {

float r = 0;

switch (opertor) {

case '+':

r = a + b;

break;

case '-':

r = a - b;

break;

case '*':

r = a * b;

break;

case '/':

r = a / b;

break;

}

return r;

}

}

怎样用JAVA写出逆波兰表达式求值部分的源代码(提供代码框架)

下面的代码是用来计算表达式的,看看是不是你要的

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("/")) {

this.level = 2;

} else if (op.equals("(")) {

this.level = -3;

} else {

this.level = -1;

}

}

}

//主类

import java.util.Deque;

import java.util.LinkedList;

import java.util.List;

import java.util.regex.Matcher;

import java.util.regex.Pattern;

public class OPText {

public static void main(String[] args) {

String expression = "2+2+(8-2)/3";// 要计算的表达式

List list = new LinkedList();

//正则式

Pattern entryOfExpression = Pattern

.compile("[0-9]+(\\.[0-9]+)?|\\(|\\)|\\+|-|\\*|/");

Deque stack = new LinkedList();//栈

Matcher m = entryOfExpression.matcher(expression);

while (m.find()) {

//提取语素

String nodeString = expression.substring(m.start(), m.end());

if (nodeString.matches("[0-9].*")) {

list.add(Double.valueOf(nodeString));//如果是数字直接送入列表

} else {

OPNode opn = new OPNode(nodeString);//如果是运算符

int peekLevel = (stack.peek() == null) ? 0 : ((OPNode) stack

.peek()).level;

if (opn.level =peekLevel) {

stack.push(opn);//新的运算符比旧的优先级别高则入栈

} else {

if (opn.level == -1) {

OPNode temp = (OPNode) stack.pop();

while (temp.level != -3) {//如果为"("则一直出栈一直到")"

list.add(temp);

System.out.println(nodeString);

temp = (OPNode) stack.pop();

}

} else if (opn.level == -3) {

stack.push(opn);

} else {//如果新运算符比栈顶运算符底则一直出栈

OPNode temp = (OPNode) stack.pop();

while (temp.level opn.level) {

list.add(temp);

if (stack.isEmpty()) {

break;

}

temp = (OPNode) stack.pop();

}

stack.push(opn);

}

}

}

}

OPNode temp = null;

while (!stack.isEmpty()) {

temp = (OPNode) stack.pop();

list.add(temp);

}//后续表达式计算

stack.clear();

for (Object o : list) {

if (o instanceof Double) {

stack.push(o);//为数字入栈

} else {

double op2 = ((Double) stack.pop()).doubleValue();

double op1 = ((Double) stack.pop()).doubleValue();

switch (((OPNode) o).op) {

case '+':

stack.push(op1 + op2);

break;

case '-':

stack.push(op1 - op2);

break;

case '*':

stack.push(op1 * op2);

break;

case '/':

stack.push(op1 / op2);

break;

}

}

}

System.out.println("结果为:" + stack.pop());

}

}

呃,太晚了,没心思去改了

明天再说


网站名称:逆波兰java代码 逆波兰式代码
网址分享:http://cdkjz.cn/article/hehhgg.html
多年建站经验

多一份参考,总有益处

联系快上网,免费获得专属《策划方案》及报价

咨询相关问题或预约面谈,可以通过以下方式与我们联系

业务热线:400-028-6601 / 大客户专线   成都:13518219792   座机:028-86922220