How to Change a 0 to a 1 in a Java Code for Fractions

Changing a 0 to a 1 in the denominator of a fraction helps prevent a division by zero error in your Java program. In a fraction such as "2/3," the number 2 is the numerator and the number 3 is the denominator. Dividing by 0 is undefined in mathematics. The denominator can not be 0 and, if it is, change it to a 1 or ask for new input.

Instructions

    • 1

      Open your Java file in an editor, such as Eclipse, Netbeans or JBuilder X.

    • 2

      Import the I/O namespace to enable access to the "readLine" function by adding the code at the top of your file:

      import java.io.*;

    • 3

      Retrieve a numerator and denominator value from the user by adding the code in your function:

      BufferedReader buffread = new BufferedReader(new InputStreamReader(System.in));

      String numerator = null;

      String denominator = null;

      int num = 0;

      int den = 1;

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

      numerator = buffread.readLine();

      System.out.print("\nEnter the fraction's denominator: ");

      denominator = buffread.readLine();

    • 4

      Convert the user input from a String into an integer by adding the code:

      num = Integer.parseInt(numerator);

      den = Integer.parseInt(denominator);

    • 5

      Check if the denominator is equal to 0 and, if so, replace it with 1 by adding the code:

      if (den == 0) den = 1;

    • 6

      Save the file, compile and execute the program to change a denominator of 0 to 1.

Related Searches:

References

Comments

Related Ads

Featured