2015-02-02 2 views
0

У меня есть следующий класс, который я пытаюсь использовать для выполнения вычислений между фракциями, но время от времени я получаю деление на нулевое исключение из функции упрощения и я не могу понять, почему он делает этоКалькулятор Java-фракции генерирует исключение для деления на ноль при попытке упростить

public class Fraction { 

    private int top; 
    private int bottom; 

    Fraction(int t, int b) { 
     top = t; 
     bottom = b; 
     simplify(); 
    } 

    public int getTop() { 
     return top; 
    } 

    public int getBottom() { 
     return bottom; 
    } 

    public void simplify() { 
     if (bottom % top == 0) { 
      bottom /= top; 
      top /= top; 
     } else { 
      int divisor = gcd(bottom, top); 
      top /= divisor; 
      bottom /= divisor; 
     } 
    } 

    public Fraction add(Fraction f) { 
     if (bottom == f.getBottom()) { 
      return new Fraction(top + f.getTop(), bottom); 
     } else { 
      return new Fraction(((top * f.getBottom()) + (f.getTop() * bottom)), bottom * f.getBottom()); 
     } 
    } 

    public Fraction subtract(Fraction f) { 
     if (bottom == f.getBottom()) { 
      return new Fraction(top - f.getTop(), bottom); 
     } else { 
      return new Fraction(((top * f.getBottom()) - (f.getTop() * bottom)), bottom * f.getBottom()); 
     } 
    } 

    public Fraction multiply(Fraction f) { 
     return new Fraction(top * f.getTop(), bottom * f.getBottom()); 
    } 

    private static int gcd(int a, int b) { 
     if (a == 0 || b == 0) { 
      return a + b; 
     } else { 
      return gcd(b, a % b); 
     } 
    } 

    @Override 
    public String toString() { 
     return top + "/" + bottom; 
    } 
} 

ответ

0

оператор bottom % top дает деление на ноль ошибок при top равна нулю.

Вы можете это исправить, изменив первую строку метода simplify() к этому:

if (top != 0 && bottom % top == 0) { 
Смежные вопросы