java 栈 四则运算_java学习之—使用栈实现字符串数字四则运算

/**

* 使用栈存储后缀表达式

* Create by Administrator

* 2018/6/13 0013

* 下午 2:25

**/

public class StackX {

private int maxSize;

private char[] stackArray;

private int top;

public StackX(int size) // 构造函数

{

maxSize = size;

stackArray = new char[maxSize];

top = -1;

}

public void push(char j) // 将项目放在堆栈的顶部

{

stackArray[++top] = j;

}

public char pop() // 从堆栈顶部取项

{

return stackArray[top--];

}

public char peek() // 从堆栈顶部查看

{

return stackArray[top];

}

public boolean isEmpty() // 如果栈为空,则为true

{

return (top == -1);

}

public boolean isFull() // 如果堆栈已满 true

{

return (top == maxSize - 1);

}

public int size() // return size

{

return top + 1;

}

public char peekN(int n) // peek at index n

{

return stackArray[n];

}

public void displayStack(String s) {

System.out.print(s);

System.out.print("Stack (bottom-->top): ");

for (int j = 0; j < size(); j++) {

System.out.print(peekN(j));

System.out.print(' ');

}

System.out.println("");

}

}

/**

* 使用栈存储计算过程结果

* Create by Administrator

* 2018/6/14 0014

* 上午 10:37

**/

public class StackR {

private int maxSize;

private int[] stackArray;

private int top;

public StackR(int size) // 构造函数

{

maxSize = size;

stackArray = new int[maxSize];

top = -1;

}

public void push(int j) // 将项目放在堆栈的顶部

{

stackArray[++top] = j;

}

public int pop() // 从堆栈顶部取项

{

return stackArray[top--];

}

public int peek() // 从堆栈顶部查看

{

return stackArray[top];

}

public boolean isEmpty() // 如果栈为空,则为true

{

return (top == -1);

}

public boolean isFull() // 如果堆栈已满 true

{

return (top == maxSize - 1);

}

public int size() // return size

{

return top + 1;

}

public int peekN(int n) // peek at index n

{

return stackArray[n];

}

public void displayStack(String s) {

System.out.print(s);

System.out.print("Stack (bottom-->top): ");

for (int j = 0; j < size(); j++) {

System.out.print(peekN(j));

System.out.print(' ');

}

System.out.println("");

}

}

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

/**

* Create by Administrator

* 2018/6/13 0013

* 下午 2:38

**/

public class InTOPost {

private StackX stackX;

private StackR stackR;

private String input;

private String outPut = "";

public InTOPost(String in) {

this.input = in;

int stackSize = input.length();

stackX = new StackX(stackSize);

}

/**

* 中缀表达式转后缀表达式

* @return

*/

public String doTrans() {

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

char ch = input.charAt(i);//拿到每个字符

stackX.displayStack("For " + ch + " ");

switch (ch) {

case '+':

case '-':

getOpera(ch, 1);

break;

case '*':

case '/':

getOpera(ch, 2);

break;

case ')':

getParen(ch);

break;

case '(':

stackX.push(ch);

break;

default:

outPut = outPut + ch; //是数字将其写入输出

break;

}

}

while (!stackX.isEmpty()) {

stackX.displayStack("While ");

outPut = outPut + stackX.pop();

}

stackX.displayStack("End ");

return outPut;

}

private void getOpera(char opThis, int prec1) {

while (!stackX.isEmpty()) {

char opTop = stackX.pop();

if (opTop == '(') {

stackX.push(opTop);

break;

} else {

int prec2;

if (opTop == '+' || opTop == '-') {

prec2 = 1;

} else {

prec2 = 2;

}

if (prec2 < prec1) {

stackX.push(opTop);

break;

} else {

outPut = outPut + opTop;

}

}

}

stackX.push(opThis);

}

private void getParen(char ch) {

while (!stackX.isEmpty()) {

char chx = stackX.pop();

if (chx == '(') {

break;

} else {

outPut = outPut + chx;

}

}

}

/**

* 计算后缀表达式的结果

* @param output

* @return

*/

public int doParse(String output) {

stackR = new StackR(20); //新建堆栈

char ch;

int num1, num2, interAns;

for (int i = 0; i < output.length(); i++) { //遍历后缀表达式的字符串

ch = output.charAt(i); // 读取到每一个字符

stackR.displayStack(ch + " ");

if (ch >= '0' && ch <= '9') { // 判断是不是数字

stackR.push((int) (ch - '0')); // 放入到栈里

} else {

num2 = stackR.pop(); // 如果不是数字,就从栈里取出两个数字

num1 = stackR.pop();

switch (ch) { // 判断是哪个运算符,并计算

case '+':

interAns = num1 + num2;

break;

case '-':

interAns = num1 - num2;

break;

case '*':

interAns = num1 * num2;

break;

case '/':

interAns = num1 / num2;

break;

default:

interAns = 0;

}

stackR.push(interAns); // 把计算结果放入栈里

}

}

interAns = stackR.pop(); // 获得最终结果

return interAns;

}

/**

* 获取用户输入

* @return

* @throws IOException

*/

public static String getString() throws IOException {

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

String s = br.readLine();

return s;

}

public static void main(String[] args) throws IOException {

String input, output;

while (true) {

System.out.print("Enter infix: ");

System.out.flush();

input = getString();

if (input.equals("")) {

break;

}

InTOPost toPost = new InTOPost(input);

output = toPost.doTrans();

System.out.println("Postfix is " + output + "\n");

int result = toPost.doParse(output);

System.out.println("结果:" + result);

}

}

运行测试:

请输入:  (4+2*3)/2

For ( Stack (bottom-->top):

For 4 Stack (bottom-->top): (

For + Stack (bottom-->top): (

For 2 Stack (bottom-->top): ( +

For * Stack (bottom-->top): ( +

For 3 Stack (bottom-->top): ( + *

For ) Stack (bottom-->top): ( + *

For / Stack (bottom-->top):

For 2 Stack (bottom-->top): /

While Stack (bottom-->top): /

End Stack (bottom-->top):

Postfix is 423*+2/

4 Stack (bottom-->top):

2 Stack (bottom-->top): 4

3 Stack (bottom-->top): 4 2

* Stack (bottom-->top): 4 2 3

+ Stack (bottom-->top): 4 6

2 Stack (bottom-->top): 10

/ Stack (bottom-->top): 10 2

结果:5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: Java中的正则表达式可以用来匹配四则运算字符串,具体的代码可以例如:String pattern = "[+-/*]"; Pattern r = Pattern.compile(pattern); Matcher m = r.matcher(str); ### 回答2: Java匹配字符串中的四则运算代码可以通过正则表达式和递归的方式实现。以下是一个简单的示例代码: ```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class Main { public static void main(String[] args) { String expression = "3 + 4 * 2 - 6 / 3"; // 使用正则表达式匹配数字和运算符 Pattern pattern = Pattern.compile("(\\d+)|([+\\-*/])"); Matcher matcher = pattern.matcher(expression); // 递归计算表达式结果 int result = calculate(matcher); System.out.println("结果:" + result); } public static int calculate(Matcher matcher) { int num1 = 0; int num2 = 0; char operator = ' '; while (matcher.find()) { String match = matcher.group(); if (match.matches("\\d+")) { num2 = Integer.parseInt(match); switch (operator) { case '+': num1 += num2; break; case '-': num1 -= num2; break; case '*': num1 *= num2; break; case '/': num1 /= num2; break; default: num1 = num2; break; } } else { operator = match.charAt(0); } } return num1; } } ``` 该代码会将字符串表达式拆分为数字和运算符,并递归计算表达式的结果。在计算过程中,乘法和除法的优先级高于加法和减法。最后将计算结果输出。 ### 回答3: 下面的代码演示了如何使用Java匹配字符串中的四则运算表达式: ```java import java.util.regex.Matcher; import java.util.regex.Pattern; public class ArithmeticMatcher { public static void main(String[] args) { // 定义待匹配的字符串 String expression = "2 + 3 * (4 - 1)"; // 定义匹配四则运算表达式的正则表达式 String regex = "\\d+(\\.\\d+)?(\\s*[-+*/]\\s*\\d+(\\.\\d+)?)*"; // 创建Pattern对象 Pattern pattern = Pattern.compile(regex); // 创建Matcher对象 Matcher matcher = pattern.matcher(expression); // 判断是否匹配成功 if (matcher.matches()) { System.out.println("表达式匹配成功!"); } else { System.out.println("表达式匹配失败!"); } } } ``` 此代码使用Java中的正则表达式来匹配四则运算表达式。首先定义了一个待匹配的字符串`expression`,然后定义了一个用于匹配四则运算表达式的正则表达式`regex`。接下来,通过调用`Pattern.compile(regex)`方法,将正则表达式编译为一个`Pattern`对象。然后,通过调用`pattern.matcher(expression)`方法,创建一个`Matcher`对象来执行匹配操作。最后,通过调用`matcher.matches()`方法,判断匹配是否成功,并输出相应的结果。 在这个例子中,我们使用了一个比较简单的正则表达式来匹配四则运算表达式。如果需要更复杂的匹配规则,可以根据具体需求进行调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值