Kashad T Kashad T - 1 month ago 11
Java Question

Repeat loop until input valid for fraction class

I am doing a simple fraction test class. I want my program to do this.

IF a user input 0 > the loop repeats until the user enter a number that not 0

In my class, it not doing that. I tried to mixed it with

do while
conditions with
if
statements plus initializing if the statement
true
or
false
. Im stuck so please I need help.

Here my fraction Class:

import java.util.*;


public class FractionTest {
public static void main(String args[]) {
Scanner input = new Scanner(System.in);

boolean valid = true;
int num, den;

den = 0;

do {
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
if (den == 0 && valid) {
System.out.println("denominator cannot be zero");
System.out.println("Please enter the numerator: ");
num = input.nextInt();
System.out.println("Please enter the denominator: ");
den = input.nextInt();
}

} while (den != 0 && !valid);
System.out.println("Decimal is " + result(num, den));
}

public static double result(int x, int y) {
return (x / y);

}
}


Here the program once I run the Test

Answer

change the code in the main-method to this:

    Scanner input = new Scanner(System.in);
    int num, den;

    do {
        System.out.println("Please enter the numerator: ");
        num = input.nextInt();
        System.out.println("Please enter the denominator: ");
        den = input.nextInt();
        if (den!=0)
            System.out.println("Decimal is " + result(num, den));
        else
            System.out.println("Denominator shouldnt be 0");
    } while (den == 0);
    input.close();
  1. There was no need to initialized 'den' as the value is anyways replaced.
  2. There was no need of having 'boolean variable' as its value never change
  3. if den==0, no need to re-ask for inputs within the loop as the loop should anyways re-run
Comments