Java怎么实现输入一个string表达式然后输出计算的结果

2024-12-03 06:57:53
推荐回答(5个)
回答(1):

import java.io.*;
import java.util.*;
class BinaryTree{
BinaryTree left=null;
BinaryTree right=null;
char data=0;
}
public class Calculator{
String porder="";
public void postorder(BinaryTree bt){
//递归后序遍历二叉树
if(bt!=null){
postorder(bt.left);
postorder(bt.right);
porder+=bt.data;
}
}
public int calc(String s){
//计算后缀表达式的值
int i=0,len=0,a=0,b=0;
Stack stack=new Stack();
len=s.length();
for(;i char c=s.charAt(i);
switch(c){
case '+':
a=(int)stack.pop();
b=(int)stack.pop();
stack.push(a+b);
break;
case '-':
b=(int)stack.pop();
a=(int)stack.pop();
stack.push(a-b);
break;
case '*':
a=(int)stack.pop();
b=(int)stack.pop();
stack.push(a*b);
break;
case '/':
b=(int)stack.pop();
a=(int)stack.pop();
stack.push((int)a/b);
break;
default:
//该字符是数字
stack.push(c-'0');
}
}
return stack.pop();
}
public BinaryTree create(String s){
//构造二叉树结点(递归)
int i=0,pos=0,len=0;
String l="",r="";
BinaryTree node=new BinaryTree();
len=s.length();
if(len==0) return null;
if(len==1){
//递归边界
node.data=s.charAt(0);
return node;
}
//去括号
while((pos=s.indexOf(")"))!=-1){
i=pos;
while((s.charAt(i)!='(')&&(i>0)) i--;
String sub=s.substring(i+1,pos);//括号中的表达式
porder="";
postorder(create(sub));//得到后缀表达式
int sum=calc(porder);//计算后缀表达式的值,替换原来括号中的表达式
s=s.substring(0,i)+String.valueOf(sum)+s.substring(pos+1);
len=s.length();//重新计算s的长度
}
//从后往前扫描得到的第一个优先级最低的运算符号的位置
pos=-1;
for(i=len-1;i>0;i--){
char c=s.charAt(i);
if((c=='+')||(c=='-')){
pos=i;
break;
}
else if(((c=='*')||(c=='/'))&&(pos==-1)) pos=i;
}
//在pos位置将s分为左右两部分,递归构造左右两个部分的二叉树
l=s.substring(0,pos);
r=s.substring(pos+1);
node.data=s.charAt(pos);
node.left=create(l);
node.right=create(r);
return node;
}
public static void main(String args[]) throws Exception{
BufferedReader reader=new BufferedReader(new InputStreamReader(System.in));
String s=reader.readLine();
Calculator c=new Calculator();
BinaryTree bt=c.create(s);
c.postorder(bt);
System.out.println(c.calc(c.porder));
}
}

回答(2):

public class houzhuibiaodashizi
{
public static void main(String[] args)
{
//中缀 => 后缀表达式
String s = "( 1.5*2+(20+10*2*10+44)/(12*11)-1)*2"; //中缀
System.out.println(s);
System.out.println(jisuan(s));
}
static double jisuan(String s)
{
String hs= ""; //后缀
char[] Operators = new char[s.length()];
int Top = -1;
for (int i = 0; i < s.length(); i++)
{
char C = s.charAt(i);
switch(C)
{
case ' ' : break;
case '+' : //操作符
case '-' :
while (Top >= 0) //栈不为空时
{
char c = Operators[Top--]; //pop Operator
if (c == '(')
{
Operators[++Top] = c; //push Operator
break;
}
else {hs = hs + c;}
}
Operators[++Top] = C; //push Operator
hs += " ";break;
case '*' : //操作符
case '/' :
while (Top >= 0) //栈不为空时
{
char c = Operators[Top--]; //pop Operator
if (c == '(')
{
Operators[++Top] = c; //push Operator
break;
}
else
{
if (c == '+' || c == '-')
{
Operators[++Top] = c; //push Operator
break;
}
else
{
hs = hs + c;
}
}
}
Operators[++Top] = C; //push Operator
hs += " ";
break;
case '(' : //操作符
Operators[++Top] = C;
hs+= " ";
break;
case ')' : //操作符
while (Top >= 0) //栈不为空时
{
char c = Operators[Top--]; //pop Operator
if (c == '(')
{
break;
}
else
{
hs= hs + c;
}
}
hs += " ";
break;
default : //操作数
hs= hs + C;
break;
}//switch
}/////////////////////////////for
while (Top >= 0)
{
hs= hs + Operators[Top--]; //pop Operator
}

System.out.println("hs="+hs); //后缀
////////////////////////////////////////////// 后缀////////////////////////////////////
//后缀表达式计算
double[] Operands = new double[hs.length()];
double x, y, v;
Top = - 1;
String Operand = "";
for (int i = 0; i < hs.length(); i++)
{
char c = hs.charAt(i);
if ((c >= '0' && c <= '9') || c == '.')
{
Operand += c;
}

if ((c == ' ' && Operand != "") || i == hs.length() - 1)
{
Operands[++Top] = java.lang.Double.parseDouble(Operand) ; //push Operands
Operand = "";
}

if (c == '+' || c == '-' || c == '*' || c == '/')
{
if ((Operand != ""))
{
Operands[++Top] = java.lang.Double.parseDouble(Operand) ; //push Operands
Operand = "";
}
y = Operands[Top--]; //pop 双目运算符的第二操作数 (后进先出)注意操作数顺序对除法的影响
x = Operands[Top--]; //pop 双目运算符的第一操作数
switch (c)
{
case '+' :
v = x + y;
break;
case '-' :
v = x - y;
break;
case '*' :
v = x * y;
break;
case '/' :
v = x / y; // 第一操作数 / 第二操作数 注意操作数顺序对除法的影响
break;
default :
v = 0;
break;
}
Operands[++Top] = v; //push 中间结果再次入栈
}////////////////////if
} ///////////////////////for
v = Operands[Top--]; //pop 最终结果
System.out.println(v);
return v;
} /////////////////////////jisuan
}/////////////////////////////////////////houzhui/////////////

回答(3):

//以前写的一个很鸡肋的计算器 你瞅瞅 嘿嘿

import java.io.*;
/**
* 计算器
* @param a 第一个数字
* @param b 第二个数字
* @param c 符号
*/
public class jisuanqi{
/**
* 计算类
*/
public void jisuan(int a,int b,String c){

if(c.equals("+")){
System.out.print(a+b);
}else
if(c.equals("-")){
System.out.print(a-b);
}else
if(c.equals("*")){
System.out.print(a*b);
}else
if(c.equals("/")){
System.out.print(a/b);
}
}
/**
* 程序入口
*/
public static void main(String args[])throws IOException{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String a1,a2;
String c;
int b1,b2;
System.out.print("请输入第一个数字:");
a1=br.readLine();
b1=Integer.parseInt(a1);
System.out.print("请输入第二个数字:");
a2=br.readLine();
b2=Integer.parseInt(a2);
System.out.print("请输入符号:");
c=br.readLine();
jisuanqi js=new jisuanqi();
js.jisuan(b1, b2, c);
}
}

回答(4):

Scanner sc = new Scanner(System.in);
System.out.println("请输入表达式");
String str = sc.next();
ScriptEngineManager sem = new ScriptEngineManager();
ScriptEngine daqi = sem.getEngineByName("nashorn");
Object eval = daqi.eval(str);
System.out.println(eval.toString());

回答(5):

呵呵 我来了 我这个应该是贫民版的了
public class Test{

public static int yunsuanjibie(String s) {
int r = 0;
int p = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*'
|| s.charAt(i) == '/') {
p++;
}
}
String k[] = new String[2 * p + 1];
int k1 = 0;
int first = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '+' || s.charAt(i) == '-' || s.charAt(i) == '*'
|| s.charAt(i) == '/') {
k[k1] = s.substring(first, i);
k1++;
k[k1] = "" + s.charAt(i);
k1++;
first = i + 1;
}
}
k[k1] = s.substring(first, s.length());
int kp = p;
while (kp > 0) {
for (int i = 0; i < k.length; i++) {
if (k[i].equals("*") || k[i].equals("/")) {
int l;
for (l = i - 1; l > -1; l--) {
if (!(k[l].equals("p")))
break;
}
int q;
for (q = i + 1; q < k.length; q++) {
if (!(k[l].equals("p")))
break;
}
if (k[i].equals("*")) {
k[i] = ""
+ (Integer.parseInt(k[l]) * Integer
.parseInt(k[q]));
k[l] = "p";
k[q] = "p";
kp--;
} else {
k[i] = ""
+ (Integer.parseInt(k[l]) / Integer
.parseInt(k[q]));
k[l] = "p";
k[q] = "p";
kp--;
}
break;
}
}
for (int i = 0; i < 2 * p + 1; i++) {
if (k[i].equals("+") || k[i].equals("-")) {
int l;
for (l = i - 1; l > -1; l--) {
if (!(k[l].equals("p")))
break;
}
int q;
for (q = i + 1; q < k.length; q++) {
if (!(k[q].equals("p")))
break;
}
if (k[i].equals("+")) {
k[i] = ""
+ (Integer.parseInt(k[l]) + Integer
.parseInt(k[q]));
k[l] = "p";
k[q] = "p";
kp--;
} else {
k[i] = ""
+ (Integer.parseInt(k[l]) - Integer
.parseInt(k[q]));
k[l] = "p";
k[q] = "p";
kp--;
}
break;
}
}
for (int i = 0; i < k.length; i++) {
if (!(k[i].equals("p"))) {
r = Integer.parseInt(k[i]);
break;
}
}
}
return r;
}

public static void sizeyunsuan(String s) {
while (true) {
int first = 0;
int last = 0;
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) == '(')
first = i;
if (s.charAt(i) == ')') {
last = i;
break;
}
}
if (last == 0) {
System.out.println(yunsuanjibie(s));
return;
} else {
String s1 = s.substring(0, first);
String s2 = s.substring(first + 1, last);
String s3 = s.substring(last + 1, s.length());
s = s1 + yunsuanjibie(s2) + s3;
}
}
}

public static void main(String[] args) {
String s=(new Scanner(System.in)).next();
sizeyunsuan(s);
}

}

你要输入什么就在main方法里面输入就好了