求助:关于四则运算的程序
下面是一个四则运算的程序,在道友的帮助下将它改为了有计算步骤的程序,哪位道友再帮小道进一步改进,将它改为连续计算步骤的程序,比如说,
输入:
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
&& mess.indexOf('/') == -1) {
break;
}
return NoKuohao(mess, a, b);// 1+7-5+89/3+4-6*8/2+4-6
} else
continue;
}
if (i == stringOperation.length - 1) {
if (mess.indexOf('+') != -1 || mess.indexOf('-') != -1)
return NoKuohao(mess, '+', '-');
break;
}
}
return mess;
}
// 截取第二个数
private double JieQu2(String str) {
double a = 0;
int InrerceIndex = 0;
char[] stringOperation = str.toCharArray();
boolean ispas = false;
for (int i = 0; i < stringOperation.length; i++) {
switch (stringOperation[i]) {
case '*':
case '/':
case '+':
case '-':
InrerceIndex = i;
if (i != 0)
ispas = true;
break;
default:
break;
}
if (ispas)
break;
}
if (InrerceIndex == 0) {
a = Double.parseDouble(str);
Str = str.length();
if (ispas)
Str++;
} else {
a = Double.parseDouble(str.substring(0, InrerceIndex));
Str = str.substring(0, InrerceIndex).length();
}
return a;
}
// 截取第一个数
private double JieQu1(String str) {
double a = 0;
int InrerceIndex = 0;
boolean temp = false;
char[] stringOperation = str.toCharArray();
for (int i = stringOperation.length - 1; i >= 0; i--) {
switch (stringOperation[i]) {
case '*':
case '/':
case '+':
case '-':
InrerceIndex = i;
temp = true;
break;
default:
break;
}
if (temp)
break;
}
if (InrerceIndex == 0) {
a = Double.parseDouble(str);
Str = str.length();
} else {
a = Double.parseDouble(str.substring(InrerceIndex, str.length()));
Str = str.substring(InrerceIndex, str.length()).length();
}
return a;
}
// 计算结果
private double JiSuanString(String operation, double num1, double num2) {
double sum = 0;
if (operation.equals("*")) {
sum = num1 * num2;
System.out.println(num1 + "*" + num2 + "=" + sum);
}
if (operation.equals("-")) {
sum = num1 - num2;
System.out.println(num1 + "-" + num2 + "=" + sum);
}
if (operation.equals("/")) {
sum = num1 / num2;
System.out.println(num1 + "/" + num2 + "=" + sum);
}
if (operation.equals("+")) {
sum = num1 + num2;
System.out.println(num1 + "+" + num2 + "=" + sum);
}
return sum;
}
}
[解决办法]
用STACK 不比这简单多了嘛..
[解决办法]
package org.lw.test;import java.text.DecimalFormat;import java.text.Format;import java.util.ArrayList;import java.util.List;import java.util.Scanner;/** * 四则运算的详细步骤,(算式中不带括号) * @author 古市轩 * @时间 2012-4-28下午 07:41:22 */public class Test112 { public static void main(String[] args) { System.out.println("请输入四则运算: "); Scanner sc = new Scanner(System.in); String str = sc.nextLine(); //如果输入的四则运算有误,则提示重新输入 while(!isOk(str)){ str = sc.nextLine(); } System.out.println(" " + myTrim(str)); getResult(getAddAndSubString(myTrim(str))); } //检查输入的等式是否有效 public static boolean isOk(String str){ try{ getOperationNumber(myTrim(str)); }catch(Exception e){ System.out.println("您输入的四则运算有误,请从新输入!"); return false; } return true; } // 根据算式截取运算符 public static List<Character> getOperation(String str) { if (!"".equals(str)) { List<Character> list = new ArrayList<Character>(); for (int i = 0; i < str.length(); i++) { if (str.charAt(i) == '+' || str.charAt(i) == '-' || str.charAt(i) == '*' || str.charAt(i) == '/') { list.add(str.charAt(i)); } } return list; } else { return null; } } // 根据算式截取操作数 public static List<Double> getOperationNumber(String str){ if (!"".equals(str)) { List<Double> list = new ArrayList<Double>(); String[] s = str.split("\\+|-|\\*|/"); for (int i = 0; i < s.length; i++) { list.add(Double.parseDouble(s[i])); } return list; } else { return null; } } // 根据只有加减运算的等式计算结果 public static Double getResult(String str) { Double result = -1.0; if (str.contains("+") || str.contains("-")) { List<Character> operations = getOperation(str); List<Double> operationNumbers = getOperationNumber(str); result = operationNumbers.get(0); for (int i = 0; i < operations.size(); i++) { char ch = operations.get(i); switch (ch) { case '+': result = result + operationNumbers.get(i + 1); break; case '-': result = result - operationNumbers.get(i + 1); } operations.remove(i); operationNumbers.remove(i); operationNumbers.remove(i); operationNumbers.add(i, result); i--; System.out.println("=" + getString(operations, operationNumbers)); } } return result; } // 把等式的乘除运算计算完后返回只剩加减运算的等式,即把含有乘法和除法的等式装换成只含有加法和减法的等式 public static String getAddAndSubString(String str) { if (str.contains("*") || str.contains("/")) { List<Character> operations = getOperation(str); List<Double> operationNumbers = getOperationNumber(str); for (int i = 0; i < operations.size(); i++) { Double temp = 0.0; switch (operations.get(i)) { case '*': temp = operationNumbers.get(i); temp = temp * operationNumbers.get(i + 1); operations.remove(i); operationNumbers.remove(i); operationNumbers.remove(i); operationNumbers.add(i, getDoubleByPoint(temp)); i--; System.out.println("=" + getString(operations, operationNumbers)); break; case '/': temp = operationNumbers.get(i); if (operationNumbers.get(i + 1) != 0) { temp = temp / operationNumbers.get(i + 1); operations.remove(i); operationNumbers.remove(i); operationNumbers.remove(i); operationNumbers.add(i, getDoubleByPoint(temp)); i--; System.out.println("=" + getString(operations, operationNumbers)); } else { System.out.println("除数不能为0!"); return ""; } } } return getString(operations, operationNumbers); } else { return str; } } //根据操作符和操作数拼接成等式字符串 public static String getString(List<Character> operations, List<Double> operationNumbers){ StringBuilder sb = new StringBuilder(); if (operations.size() != 0) { sb.append(getStringFromDouble(operationNumbers.get(0))); for (int i = 0; i < operations.size(); i++) { sb.append(operations.get(i)).append( getStringFromDouble(operationNumbers.get(i + 1))); } return sb.toString(); } else { return getStringFromDouble(operationNumbers.get(0)).toString(); } } //去掉输入的等式中所有的空格 public static String myTrim(String str){ return str.replaceAll("\\s*", ""); } //保留两位小数,(如3.14159显示3.14) public static double getDoubleByPoint(double d){ Format format = new DecimalFormat("#.00"); return Double.parseDouble(format.format(d)); } //使输出的等式格式良好,如3直接输出3,而不是3.0 public static String getStringFromDouble(double d){ int i = (int)d; if(i - d == 0){ return i+""; } return d+""; }}