我正在写一个分数计算器。我已经编写了一个解析代码的方法,但是很难弄清楚如何将plus运算符添加到parseExpression方法中。例如:1_1 / 2 + 1 = 2_1 / 2。如果你选择回答尽力让我指向正确的方向。如果有人对减号,除法和乘法运算符有任何建议,我也会很感激。
public class FracCalc {
public static void main(String[] args) {
// TODO: Implement.
Scanner console = new Scanner(System.in);
System.out.println("enter an equation: ");
String myInput = console.nextLine();
String simplified = parseExpression(myInput);
System.out.print(simplified);
shouldQuit(myInput);
console.close();
}
public static boolean shouldQuit(String input) {
String quit = input;
if (input.equals("quit")) {
System.out.print("Quit");
return true;
} else {
return false;
}
}
public static String parseExpression(String expr) {
//parses the expression for '_'
if(expr.indexOf("_")!=-1) {
int spot = expr.indexOf("_");
String first = expr.substring(0, spot);
int frac = expr.indexOf("/");
String numer = expr.substring(spot + 1, frac);
String denom = expr.substring(frac + 1);
String mixednum = improperMNum(numer, denom);
String mixed = first + "_" + mixednum;
return mixed;
}
//parses the expression for '/'
if (expr.contains("/")) {
int index = expr.indexOf("/");
String numerator = expr.substring(0, index);
String denominator = expr.substring(index + 1);
System.out.println(numerator + denominator);
String x = improperMNum(numerator, denominator);
return x;
} else {
String wholenumber = expr.substring(0);
return wholenumber;
}
}
public static String improperMNum(String numerator, String denominator) {
int wholenumber = numerator.indexOf("_");