java 四则混合运算_JAVA写的四则混合运算

近来用java写了一个小程序,不敢独享.

这是一个四则混合运算程序,没什么做优化,也没做什么注释,(人啊,总喜欢偷懒的.)

这个版本我已经定为了2.21版本.呵呵.

从最先的1.0到2.0的改动很大.除了运算思想没动处,其它的都在2.0做了重新设计.

这种程序其实网上一大把(算法也好得多)。此仅为无聊找点事情做而已。

/**

*四则混合运算程序

*作者:黄剑武

*时间:2005年4月29日

*版本:2.21

*修改日志:2.0

http://www.gaodaima.com/40231.htmlJAVA写的四则混合运算

* 1.更改表达式用户输入方式.

* 2.对用户输入的表达式进行有效性字符过滤.

* 3.使用Double代替原int数值,并且使用严格浮点运算提高运算精度.

* 4.解除对运算数字只能是一位的限制.

* 5.优化了部分代码.

*修改日志:2.1

*   1.加入表达式括号匹配功能.

*修改日志:2.2

*   1.加入表达式处理功能.

*修改日志:2.21

*   1.修改部分语法以支持JDK1.5中的泛型用法.

*/

import java.lang.reflect.Array;

import java.util.*;

import java.util.regex.*;

import java.lang.*;

import java.io.*;

//测试用例:1-3*(4-(2+5*3)+5)-6/(1+2)=23

//测试用例:11.2+3.1*(423-(2+5.7*3.4)+5.6)-6.4/(15.5+24)=1273.4199746835445

class Calculator

{

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

{

String str_input;

double f_output;

while (true)

{

System.out.print("输入表达式: ");

System.out.flush();

str_input = getString();

if (str_input.equals(""))

{

break;

}

Calculator calculator = new Calculator();

//以下对输入字符串做规则处理

str_input = calculator.checkExpression(str_input);

if (str_input.equals(""))

{

System.out.println("   表达式出错  ");

}

//以下对输入字符串做表达式转换

Vector v_compute = calculator.getExpression(str_input);

/*

for (int i=0;i

{

System.out.println("  "+v_compute.get(i));

}

*/

//以下进行后缀表达式转换

Vector v_tmp_prefix = calculator.transformPrefix(v_compute);

/*

for (int i=0;i

{

System.out.println(v_tmp_prefix.get(i));

}

*/

//以下进行后缀表达式运算

f_output = calculator.evaluatePrefix(v_tmp_prefix);

System.out.println("结果 = " + f_output);

}

}

/**

*静态方法,用来从控制台读入表达式

*/

public static String getString() throws IOException

{

InputStreamReader isr = new InputStreamReader(System.in);

BufferedReader br = new BufferedReader(isr);

String s = br.readLine();

return s;

}

/**

*输入字符串转换.把从控制台读入的字符串转成表达式存在一个队列中.

*例:123+321 存为"123""+""321"

*/

public Vector getExpression(String str)

{

Vector v_temp = new Vector();

char[] temp = new char[str.length()];

str.getChars(0,str.length(),temp,0);

String fi = "";

int x=0,i=0;

String regex_fig = "[//.//d]";                  //匹配数字和小数点

String regex_operator = "[//+//-//*///(//)]";    //匹配运算符(+,-,*,/)和括号("(",")")

Pattern p_fig = Pattern.compile(regex_fig);

Pattern p_operator = Pattern.compile(regex_operator);

Matcher m = null;

boolean b;

while (i

{

Character c = new Character(temp[i]);

String s = c.toString();

//System.out.println("char c = "+s);

m = p_operator.matcher(s);

b = m.matches();

if (b)

{

//System.out.println("matches operator");

v_temp.add(fi);

fi="";

v_temp.add(s);

}

m = p_fig.matcher(s);

b = m.matches();

if (b)

{

//System.out.println("matches fig");

fi=fi+s;

}

i++;

}

v_temp.add(fi);

return v_temp;

}

/**

*转换中序表示式为前序表示式

*/

public Vector transformPrefix(Vector v_expression)

{

Vector v_prefix = new Vector();

Stack s_tmp = new Stack();

String regex_float = "//d+(//.//d+)?";      //匹配正浮点数

Pattern p_float = Pattern.compile(regex_float);

Matcher m = null;

boolean b;

String str_elem = "";

for (int i=0;i

{

str_elem = v_expression.get(i).toString();

m = p_float.matcher(str_elem);

b = m.matches();

if (b)

{

v_prefix.add(str_elem);

}

if (str_elem.equals("+")||str_elem.equals("-"))

{

if (s_tmp.isEmpty())

{

s_tmp.push(str_elem);

}

else

{

while(!s_tmp.isEmpty())

{

String str_tmp = s_tmp.peek();

if ( str_tmp.equals("("))

{

break;

}

else

{

v_prefix.add(s_tmp.pop());

}

}

s_tmp.push(str_elem);

}

}

if (str_elem.equals("*")||str_elem.equals("/"))

{

if (s_tmp.isEmpty())

{

s_tmp.push(str_elem);

}

else

{

while(!s_tmp.isEmpty())

{

String str_tmp = s_tmp.peek();

if ( str_tmp.equals("(") || str_tmp.equals("+") || str_tmp.equals("-"))

{

break;

}

else

{

v_prefix.add(s_tmp.pop());

}

}

s_tmp.push(str_elem);

}

}

if (str_elem.equals("("))

{

s_tmp.push(str_elem);

}

if (str_elem.equals(")"))

{

while(!s_tmp.isEmpty())

{

String str_tmp = s_tmp.peek();

if (str_tmp.equals("("))

{

s_tmp.pop();

break;

}

else

{

v_prefix.add(s_tmp.pop());

}

}

}

}

while(!s_tmp.isEmpty())

{

v_prefix.add(s_tmp.pop());

}

return v_prefix;

}

/**

*前缀表示式求值

*/

public strictfp double evaluatePrefix(Vector v_prefix)

{

String str_tmp = "";

double num1,num2,interAns = 0;

Stack s_compute = new Stack();

int i = 0;

while(i

{

str_tmp = v_prefix.get(i).toString();

if (!str_tmp.equals("+") && !str_tmp.equals("-") && !str_tmp.equals("*") && !str_tmp.equals("/"))

{

interAns = s_compute.push(Double.parseDouble(str_tmp));

}

else

{

num2=(Double)(s_compute.pop());

num1=(Double)(s_compute.pop());

if (str_tmp.equals("+"))

{

interAns = num1+num2;

}

if (str_tmp.equals("-"))

{

interAns = num1-num2;

}

if (str_tmp.equals("*"))

{

interAns = num1*num2;

}

if (str_tmp.equals("/"))

{

interAns = num1/num2;

}

s_compute.push(interAns);

}

i++;

}

return interAns;

}

/**

*括号匹配检测

*/

public boolean checkBracket(String str)

{

Stack s_check = new Stack();

boolean b_flag = true;

for (int i=0;i

{

char ch = str.charAt(i);

switch(ch)

{

case '(':

s_check.push(ch);

break;

case ')':

if (!s_check.isEmpty())

{

char chx = s_check.pop();

if (ch==')' && chx!='(')

{

b_flag = false;

}

} else {

b_flag = false;

}

break;

default:

break;

}

}

if (!s_check.isEmpty())

{

b_flag = false;

}

return b_flag;

}

/**

*表达式正确性规则处理与校验

*/

public String checkExpression(String str)

{

Stack s_check = new Stack();

Stack s_tmp = new Stack();

String str_result = "";

String str_regex = "^[//.//d//+//-//*///(//)]+$";                  //匹配合法的运算字符"数字,.,+,-,*,/,(,),"

Pattern p_filtrate = Pattern.compile(str_regex);

Matcher m = p_filtrate.matcher(str);

boolean b_filtrate = m.matches();

if (!b_filtrate)

{

str_result = "";

return str_result;

}

String str_err_float = ".*(//.//d*){2,}.*";                      //匹配非法的浮点数.

Pattern p_err_float = Pattern.compile(str_err_float);

Matcher m_err_float = p_err_float.matcher(str);

boolean b_err_float = m_err_float.matches();

if (b_err_float)

{

str_result = "";

return str_result;

}

for (int i=0;i

{

char ch = str.charAt(i);

if (checkFig(ch))

{

if (!s_tmp.isEmpty()&&s_tmp.peek()==')')

{

str_result = "";

return str_result;

}

s_tmp.push(ch);

str_result = str_result+ch;

}

switch(ch)

{

case '(':

if (!s_tmp.isEmpty()&&s_tmp.peek()=='.')

{

str_result = "";

return str_result;

}

s_check.push(ch);

if (s_tmp.isEmpty()||(!this.checkFig(s_tmp.peek())&&s_tmp.peek()!=')'))

{

str_result = str_result+ch;

} else {

str_result = str_result+"*"+ch;

}

s_tmp.push(ch);

break;

case ')':

if (!s_check.isEmpty())

{

char chx = s_check.pop();

if (ch==')' && chx!='(')

{

str_result = "";

return str_result;

}

} else {

str_result = "";

return str_result;

}

if (s_tmp.peek()=='.'||(!this.checkFig(s_tmp.peek())&&s_tmp.peek()!=')'))

{

str_result = "";

return str_result;

}

s_tmp.push(ch);

str_result = str_result+ch;

break;

case '+':

case '-':

if (!s_tmp.isEmpty()&&(s_tmp.peek()=='+'||s_tmp.peek()=='-'||s_tmp.peek()=='*'||s_tmp.peek()=='/'||s_tmp.peek()=='.'))

{

str_result = "";

return str_result;

}

if (s_tmp.isEmpty()||s_tmp.peek()=='(')

{

str_result = str_result+"0"+ch;

} else {

str_result = str_result+ch;

}

s_tmp.push(ch);

break;

case '*':

case '/':

if (s_tmp.isEmpty()||s_tmp.peek()=='.'||(!this.checkFig(s_tmp.peek())&&s_tmp.peek()!=')'))

{

str_result = "";

return str_result;

}

s_tmp.push(ch);

str_result = str_result+ch;

break;

case '.':

if (s_tmp.isEmpty()||!this.checkFig(s_tmp.peek()))

{

str_result = str_result+"0"+ch;

} else {

str_result = str_result+ch;

}

s_tmp.push(ch);

break;

default:

break;

}

}

if (!s_check.isEmpty())

{

str_result = "";

return str_result;

}

return str_result;

}

private static boolean checkFig(Object ch)

{

String s = ch.toString();

String str_regexfig = "//d";                  //匹配数字

Pattern p_fig = Pattern.compile(str_regexfig);

Matcher m_fig = p_fig.matcher(s) ;

boolean b_fig = m_fig.matches();

return b_fig;

}

};

欢迎大家阅读《JAVA写的四则混合运算》,跪求各位点评,若觉得好的话请收藏本文,by 搞代码

原创文章,转载请注明: 转载自搞代码

e7ce419cf2d6ad34d01da2ceb8829eed.png

微信 赏一包辣条吧~

023a57327877fb4402bcc76911ec18ea.png

支付宝 赏一听可乐吧~

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值