Search code examples
javaif-statementwhile-loopdivide-by-zero

Help with using a while loop and if statement


I'm trying to write a program that reads 2 numbers from the user and divides them. Here is the code I have so far:

import java.util.Scanner;

public class divideByZero {

public static int quotient(int numerator, int denominator)
{
   return numerator / denominator;
}

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

    System.out.print("Please enter the first number: ");

    int numerator = scanner.nextInt();

    System.out.print("Please enter the second number: ");

    int denominator = scanner.nextInt();

    int result = quotient( numerator, denominator );

    float result2 = (float)result;

    System.out.printf("\n The first number %d divided by the second number "
            + "%d = %f\n", numerator, denominator, result2 );

}

How can I change it so that it is a while loop, using an if statement to check the second number and if it is 0, ask the user to input a different number?


Solution

  • This isn't an answer to your question, but you need to convert at least one of those numbers to a double. Right now you'll just be doing integer division, i.e. 5/3 = 1. You can do this with double num = (double) denominator.

    Second, this is a good use of a do while loop. Keep asking for the number until it isn't a 0. You know you want a do while loop when your first iteration through the loop doesn't have a condition (i.e. you know you'll be doing the logic AT LEAST once.)

    System.out.println("Please enter the second number: ");
    do {
         int denominator = scanner.in();
         if (denominator == 0) System.out.println("Please enter a non-zero number: ");
    } while (denominator == 0);