Return a String representation of a Rational number in floating-point format. (Consider providing formatting capabilities that enable the user of the class to specify the number of digits of precision to the right of the decimal point.)
I am trying to take a user defined floating-point formatted number from a rational number that is also user defined and put through arithmetic methods. Currently my issue is where to input the prompt for the user to input the value for the floating-point variable and allowing it to be put through the correct method which I defined as toFloat to format the rational number.
public String toFloat() { float num; int n; Scanner input = new Scanner(System.in); System.out.print("Enter precision: "); n = input.nextInt(); float numerator = this.getNumerator(); float denominator = this.getDenominator(); num = numerator / denominator; DecimalFormat df = new DecimalFormat(); df.setMaximumFractionDigits(n); return df.format(num); }
Currently I have it inside the toFloat method but the output example provided to me shows the scanner for precision being called when inputting the values for the rational number.
The constructor Rational is defined as numerator and denominator but not precision as if I do this it prompts me to input precision twice which I do not want. My question is how could I implement the scanner for toFloat outside of the method to be called before and still applied to toFloat.