日期:2014-05-20  浏览次数:20826 次

【求助】求高手将程序改为有输出计算过程的程序,并优化程序,谢谢!
将下面程序改为有计算过程的程序,比如输入:1+(2*3),输出:=1+6=7.
程序有很多毛病与不足,还请高手给优化,谢谢!

import java.util.Scanner;

public class Buhui {
public int Str = 0;
public int br = 0;

// 追加默认构造器
private Buhui() {

}

public static void main(String[] args) {


Buhui sObject = new Buhui();
Scanner input = new Scanner(System.in);
do {
System.out.println("请输入四则运算式:");
String numberString = input.next().trim();
if (sObject.PanduanShuRu(numberString) == false) {
System.out.println("您输入有误,请正确输入!");
} else {
System.out.println(sObject.PanduanKuohao(numberString));
}
} while (true);
}

// 判断是否正确输入运算方式
private boolean PanduanShuRu(String messString) {
boolean ispass = false;
boolean operationIspass = true;
int ai = 0;
char[] IsString = messString.toCharArray();
int num1 = 0;
int num2 = 0;
for (int i = 0; i < IsString.length; i++) {

if ('(' == IsString[i])
num1++;
if (')' == IsString[i])
num2++;

if ('/' == IsString[i] && IsString[i + 1] == '0')
operationIspass = false;

if (IsString[i] == '+' || IsString[i] == '-' || IsString[i] == '*'
|| IsString[i] == '/')
ai++;

if (i == IsString.length - 1)
if (ai == 0)
num2++;
}
if (operationIspass)
if (num1 == num2)
ispass = true;
return ispass;
}

private String PanduanKuohao(String str) {
String result = str;
char[] numberString = str.toCharArray();
int IndexStart = 0;
int EndStart = 0;
for (int i = 0; i < numberString.length; i++) {
if ('(' == numberString[i]) {

IndexStart = i;
}
if (')' == numberString[i]) {

EndStart = i;

result = result.substring(IndexStart + 1, EndStart);

result = str.substring(0, IndexStart)
+ NoKuohao(result, '*', '/')
+ str.substring(EndStart + 1, str.length());

return PanduanKuohao(result);
}
if (i == numberString.length - 1)
if (EndStart == 0)
break;
}

result = NoKuohao(str, '*', '/');
return result;
}

// 不带括号的四则运算
private String NoKuohao(String operationNumber, char a, char b) {

String mess = operationNumber;
char[] stringOperation = mess.toCharArray();

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

if (stringOperation[i] == a || stringOperation[i] == b) {
if (i != 0) {

double num1 = JieQu1(mess.substring(0, i));

int frontPosition = Str;

double num2 = JieQu2(mess.substring(i + 1,
stringOperation.length));

int backPosition = Str;

String IndexMess = mess.substring(0, i - frontPosition + 1);
String IndexResult = "";

if (IndexMess.indexOf('+') == -1
&& IndexMess.indexOf('*') == -1
&& IndexMess.indexOf('/') == -1
&& IndexMess.lastIndexOf('-') == -1)
IndexMess = "";
if (IndexMess != "")
IndexResult = IndexMess.lastIndexOf('-') == IndexMess
.length() - 1 ? IndexMess.substring(0, i
- frontPosition) : IndexMess;

mess = IndexResult
+ JiSuanString("" + stringOperation[i], num1, num2)
+ mess.substring(i + backPosition + 1);

if (mess.lastIndexOf('-') == 0 && mess.indexOf('+') == -1
&& mess.indexOf('*') == -1
&& mess.indexOf('/') == -1) {
break;
}

return NoKuohao(mess, a, b);// 1+7-5+89/3+4-6*8/2+4-6
} else