Files
PR2-Aufgaben/U20/Bruch.java

124 lines
2.7 KiB
Java

/**
* @author Elia Ali Elmas
* @version 1.0
*
* This Calss represents a Fraction
*/
public class Bruch {
private int zaehler;
private int nenner;
private final String nennerIsZero = "Der Nenner darf nicht 0 sein";
/**
*
* Initializes the fraction
*
* @param zaehler denominator for the fraction
* @param nenner numerator for the fraction
* @throws IllegalArgumentException if the denominator is 0
*/
public Bruch(int zaehler, int nenner) {
this.zaehler = zaehler;
if (nenner == 0) {
throw new IllegalArgumentException(nennerIsZero);
}
this.nenner = nenner;
}
/**
* Returns the value of the fraction
*
* @return the value of the fraction
*/
public double zahl() {
return (double) zaehler / (double) nenner;
}
/**
* Calculates the equality of two fractions
*
* @param o the other fraction
* @return true if the fractions are equal, false otherwise
*/
@Override
public boolean equals(Object o) {
if (!(o instanceof Bruch)) {
return false;
}
Bruch bruch = (Bruch) o;
return this.zahl() == bruch.zahl();
}
/**
* Calculates the hashcode of the fraction
*
* @return the hashcode
*/
@Override
public int hashCode() {
int ggt = ggt(zaehler, nenner);
return java.util.Objects.hash(zaehler / ggt, nenner / ggt);
}
/**
* Sets the value of the denominator of the fraction
*
* @param zaehler the new denominator
*/
public void setZaehler(int zaehler) {
if (zaehler != 0) {
this.zaehler = zaehler;
}
}
/**
* Sets the value of the numerator of the fraction
*
* @param nenner the new numerator
*/
public void setNenner(int nenner) throws IllegalArgumentException {
if (nenner == 0) {
throw new IllegalArgumentException(nennerIsZero);
}
this.nenner = nenner;
}
/**
* Returns the value of the denominator
*
* @return the value of the denominator
*/
public int getZaehler() {
return zaehler;
}
/**
* Returns the value of the numerator
*
* @return the value of the numerator
*/
public int getNenner() {
return nenner;
}
/**
* Returns the greatest common divisor of two integers
*
*
* @param a the first integer
* @param b the second integer
* @return the greatest common divisor typeof int
*/
private int ggt(int a, int b) {
if (b == 0) {
return a;
}
return ggt(b, a % b);
}
}