-4
我有我的代碼在這裏,我已經發布在這裏之前,並得到了幫助。變量似乎不正確,我不確定原因。我輸入了分數1/2 + 3/4,並得到答案8/4。我知道它與變量有關,因爲當我運行調試器時,它說「a」= 1,'b'= 1,'c'= 4,'d'= 4。 'a'和'd'按我想要的方式是正確的,從'a'到'd'從左到右。我想我知道問題在哪裏,但我不知道如何解決它。我想用「B」的問題與該行的代碼做變量不正確;分數計算器; JAVA
b = Integer.parseInt("1");
這裏是我完整的代碼
進口的java.util。*;
public class Calculator {
public static void main(String[] args) {
System.out.println("Please enter two fractions to add, subtract, multiply, or divide\nor\nType 'quit' to exit the program.");
Boolean on = true;
Scanner console = new Scanner(System.in);
while (on) {
String input = console.nextLine();
if (input.equalsIgnoreCase("quit")) {
on = false;
} else
System.out.println(run(input));
}
}
public static String run(String input) {
int indexOfSecondSpace = 0;
int indexOfOperation = 0;
String firstNumber = "0";
String secondNumber = "0";
int beginning = input.indexOf(" ") + 1;
int end = input.indexOf(" ", beginning);
String operator = input.substring(beginning, end);
if (input.contains("+") == true) {
indexOfOperation = input.indexOf("+");
} else if (operator.equals("-")) {
indexOfOperation = input.indexOf("-");
} else if (operator.equals("*")) {
indexOfOperation = input.indexOf("*");
} else if (operator.equals("/")) {
indexOfOperation = input.indexOf("/");
}
firstNumber = (input.substring(0, input.indexOf(" ")));
secondNumber = (input.substring(beginning + 1));
int a = 0;
int b = 0;
int c = 0;
int d = 0;
if (firstNumber.contains("/")) {
a = Integer.parseInt(firstNumber.substring(0,firstNumber.indexOf("/")));
b = Integer.parseInt(firstNumber.substring(0,firstNumber.indexOf("/")));
} else if (!firstNumber.contains("/"))
a = Integer.parseInt(input.substring(0, input.indexOf(" ")));
b = Integer.parseInt("1");
{
if (secondNumber.contains("/")) {
c = Integer.parseInt(secondNumber.substring(secondNumber.indexOf("/")+1));
d = Integer.parseInt(secondNumber.substring(secondNumber.indexOf("/")+1));
} else if (!secondNumber.contains("/")) {
c = Integer.parseInt(secondNumber.substring(secondNumber.length()));
d = Integer.parseInt("1");
}
}
String res = calculate(input, a, b, c, d) ;
return res;
}
public static String calculate(String input, int a, int b, int c, int d){
if (input.contains ("+"))
{
System.out.println("your answer is " + (a*d + b*c)+"/" +(b*d));
}
else if (input.contains("-"))
{
System.out.println("your answer is " + (a*d - b*c)+ "/" +(b*d));
}
else if (input.contains("/"))
{
System.out.println("your answer is " + (a*d)/(b*c)+ "/" +(b*d));
}
else if (input.contains("*"))
{
System.out.println("your answer is " + (a*c) +"/" +(b*d));
}
return input;
}
}
所以如何將我到處去解決這個使它打印我希望它太輸出。對不起,我對Java仍然很陌生。幫助是好事。謝謝 – diy900