import java.util.Scanner;
public class FractionToDecimal {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Please enter the numerator");
double numerator = input.nextDouble();
System.out.println("Please enter the denominator");
double denominator = input.nextDouble();
if(denominator == 0){
System.err.println("ERROR - Cannot divide by zero.");
}
else {
System.out.println("The result is " + (numerator/denominator));
}
}
}
<h2>Explanation:</h2>// import the Scanner class to allow for user input
import java.util.Scanner;
// 1. Declare a class
public class FractionToDecimal {
// 2. Write the main method
public static void main(String[] args) {
// 3. Create an object of the Scanner class called <em>input</em>
Scanner input = new Scanner(System.in);
// 4. Prompt the user to supply the numerator
System.out.println("Please enter the numerator");
// 5. Declare and initialize a variable <em>numerator </em>to hold the numerator
// supplied by the user.
// The numerator is of type double since the program does not
// specify any. With a double both integer and floating point numbers
// will be supported.
double numerator = input.nextDouble();
// 6. Prompt the user to enter the denominator
System.out.println("Please enter the denominator");
// 7. Declare and initialize a variable <em>denominator </em>to hold the
// denominator supplied by the user.
// The denominator is also of type double since the program does not
// specify any. With a double, both integer and floating point numbers
// will be supported.
double denominator = input.nextDouble();
// 8. Check if the denominator is or is not zero.
// if it is zero, display an error message
if(denominator == 0){
System.err.println("ERROR - Cannot divide by zero.");
}
// if it is not zero, then print out the result of the division
else {
System.out.println("The result is " + (numerator/denominator));
}
} // end of main method
} // end of class declaration
Please Note:
The code above has been written in Java.
The explanation segment contains comments to explain every line of the code.
But a few things are still worth noting;
i. Dividing the numerator by the denominator will convert a fraction to decimal.
ii. The object of the Scanner class <em>input </em> is used to get the inputs (numerator and denominator) from the user. Since the inputs are going to be integers or doubles, the nextDouble() method of the the Scanner class is used.
iii. If the denominator is zero, an error message will be displayed. I have used the System.err.println() method for that rather than the regular System.out.println() method. The difference is that the former will print out the error text in red color.
iv. Notice also that the else statement in the code will perform the division and also print out the result of the division along side with some text.
<em>Hope this helps!</em>