public class Fraction { public final int numerator; public final int denominator
ID: 3819981 • Letter: P
Question
public class Fraction
{
public final int numerator;
public final int denominator;
public Fraction(int num, int denom){
try{
numerator = num;
if (denom == 0){
throw new DivisionByZeroException("Denominator should not be zero.");
}
denominator = denom;
}
catch (DivisionByZeroException e){
System.out.println(e.getMessage());
}
}
}
After I compile it, it shows that variable numerator might not have been initialized.
What is the problem and how to solve it? It is given that the instance variables must be public and final.
If I want to add setters and getters, how to do it?
Explanation / Answer
variable declared as final int cannot be modified instead use just public int numerator and denominator.
Functions to set and get numerator and denominator are as fallows, add them to class Fraction.
public void setNumerator(int num)
{
numerator = num;
}
public void setDenominator(int denom)
{
denominator = denom;
}
public int getNumerator()
{
return numerator;
}
public int getDenominator()
{
return denominator;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.