变量不正确;分数计算器; JAVA

时间:2015-01-09 16:14:58

标签: java fractions

我在这里有我的代码,我之前在这里发布并且之前得到了帮助。变量似乎不正确,我不确定为什么。我输入了分数1/2 + 3/4,我得到了答案8/4。我知道它与变量有关,因为当我运行调试器时,它表示“a”= 1,'b'= 1,'c'= 4,'d'= 4。 'a'和'd'在我想要的方式上是正确的,从'a'到'd'从左到右。我想我知道问题在哪里,但我不知道如何解决它。我认为'b'的问题与这行代码有关

b = Integer.parseInt("1");

这是我的完整代码

import 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;
}
}

1 个答案:

答案 0 :(得分:1)

您的代码中包含以下内容

c = Integer.parseInt(secondNumber.substring(secondNumber.indexOf("/")+1));
d = Integer.parseInt(secondNumber.substring(secondNumber.indexOf("/")+1));

为什么你会期望c和d有不同的值?

另外值得注意的是

d = Integer.parseInt("1");

可以改写为

d = 1;