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

求助:关于四则运算的程序
下面是一个四则运算的程序,在道友的帮助下将它改为了有计算步骤的程序,哪位道友再帮小道进一步改进,将它改为连续计算步骤的程序,比如说,
输入:
5 + 5 - 5 * 5 / 5,
输出:
5 + 5 - 5 * 5 / 5 
  = 5 + 5 - 25 / 5
  = 5 + 5 - 5  
  = 10 - 5 
  = 5


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