好的,所以我知道这没有完成,我正在努力。基本上现在它只打印第二个操作数的部分。当我运行我已经实现的测试用例时,我得到一个例外。他们跑步,向我展示成功的迹象,但之后它并没有结束这个计划。只是抛出异常:
import java.util.*;
public class FracCalc {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.println("Welcome to FracCalc! Please enter an expression and I will find the answer.");
String expression = scan.nextLine();
runProgram(expression);
while (!expression.equals("quit") || expression.equals("test")) {
Scanner scanTWO = new Scanner(System.in);
System.out.println("Please enter another expression.");
String expressionTWO = scanTWO.nextLine();
runProgram(expressionTWO);
}
System.out.println("Goodbye. Thank you for choosing FracCalc for all your calculating needs. Come back soon!");
}
public static String produceAnswer(String input) {
String[] splitExpression = input.split(" ");
//To split the expression into first operand, operation, second operation.
String firstOperand = splitExpression[0];
String operator = splitExpression[1];
String secondOperand = splitExpression[2];
return splitOperand(secondOperand);
}
public static String splitOperand(String operand) {
if (operand.contains("_")) {
String[] splitOperand = operand.split("_");
String number = splitOperand[0];
String fraction = splitOperand[1];
String[] splitFraction = fraction.split("/");
String numerator = splitFraction[0];
String denominator = splitFraction[1];
String operandParts = "whole:" + number + " numerator:" + numerator + " denominator:" + denominator;
return operandParts;
} else {
if (operand.contains("/")) {
String[] splitFraction = operand.split("/");
String numerator = splitFraction[0];
String denominator = splitFraction[1];
String operandParts = "whole:0" + " numerator:" + numerator + " denominator:" + denominator;
return operandParts;
} else {
String number = operand;
String operandParts = "whole:" + number + " numerator:0" + " denominator:0";
return operandParts;
}
}
}
public static void runProgram(String userInput) {
System.out.println(userInput);
//Run test to see if program correctly codded.
if (userInput.equals("test")) {
runTests();
} if (userInput.equals("quit")) {
} else {
//Run user imput.
System.out.println(produceAnswer(userInput));
}
}
public static void runTests() {
System.out.println(test("5_3/4 - 6_5/8", "whole:6 numerator:5 denominator:8"));
System.out.println(test("-3/7 - 20", "whole:20 numerator:0 denominator:0"));
System.out.println(test("-32 - 27/21", "whole:0 numerator:27 denominator:21"));
System.out.println("Thank you for maintaining me and keeping me smart!");
}
public static String test(String input, String expectedOutput) {
String actualOutput = produceAnswer(input);
String testResult = "";
if (expectedOutput.equals(actualOutput)) {
testResult = "Success!";
} else {
testResult = "Failure!\nInput: " + input + "\nExpected Output: " + expectedOutput + "\nActual Output: " + actualOutput;
}
return testResult;
}
}`
抱歉这有点重,不知道从哪里开始看。
谢谢!