# Divide by Two_if/else Statement

Open the file DivideTwo.java. The Java source code is shown below:

package edu.ilstu;

import java.util.Scanner;

public class DivideTwo {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

int numerator = 0;

int denominator = 0;

double quotient = 0;

System.out.println("This program divides two numbers.");

System.out.print("Enter the numerator: ");

numerator = keyboard.nextInt();

System.out.print("Enter the denominator: ");

denominator = keyboard.nextInt();

quotient = (double) numerator / denominator;

System.out.println(numerator + "/" + denominator

+ " = " + quotient);

keyboard.close();

}

}

Compile and run DivideTwo.java, and observe the output. The program prompts the user for two integers that represent the numerator and the denominator of a fraction. The Scanner object named keyboard is used to read the integers provided by the user.

Modify the program to include an if/else statement to check for division by zero. If the denominator is not equal to zero, display the result of the division, otherwise display a message to the user that division by zero is not allowed.

package edu.ilstu;

import java.util.Scanner;

public class DivideTwo {

public static void main(String[] args) {

Scanner keyboard = new Scanner(System.in);

int numerator = 0;

int denominator = 0;

double quotient = 0;

System.out.println("This program divides two numbers.");

System.out.print("Enter the numerator: ");

numerator = keyboard.nextInt();

System.out.print("Enter the denominator: ");

denominator = keyboard.nextInt();

quotient = (double) numerator / denominator;

System.out.println(numerator + "/" + denominator

+ " = " + quotient);

keyboard.close();

}

}

Compile and run DivideTwo.java, and observe the output. The program prompts the user for two integers that represent the numerator and the denominator of a fraction. The Scanner object named keyboard is used to read the integers provided by the user.

Modify the program to include an if/else statement to check for division by zero. If the denominator is not equal to zero, display the result of the division, otherwise display a message to the user that division by zero is not allowed.

You'll get 1 file (3.2KB)