Quotient Calculator
Typer | Posted on | |
// QC means Quotient Calculator , so this file named Qc.java
import java.util.Scanner;
public class Qc {
public static void main(String[] args) {
try (Scanner scan = new Scanner(System.in)) {
double number1 = 0, number2 = 0;
while (true) {
// hints to enter the first number
while (true) {
System.out.println(
"Please enter the 1st non-zero number or 'bye' to quit: ");
if (scan.hasNext("bye")) {
System.out.println("Goodbye!");
return;
}
if (scan.hasNextDouble()) {
number1 = scan.nextDouble();
if (number1 != 0) {
break;
}
}
// Deal with invalid input
System.out.println("Invalid input. Please enter a valid number.");
scan.nextLine();
}
// hints to enter the second number
while (true) {
System.out.print(
"Please enter the 2nd non-zero number or 'bye' to quit: ");
if (scan.hasNext("bye")) {
System.out.println("Goodbye!");
return;
}
if (scan.hasNextDouble()) {
number2 = scan.nextDouble();
if (number2 != 0) {
break;
}
}
// Deal with invalid input
System.out.println("Invalid input. Please enter a valid number.");
scan.nextLine();
}
// Calculate sample quotient
int[][] sampleCases = {{1, 1}, {1, 4}, {3, 8}, {2, 3}, {25, 7}};
System.out.println("------------------For example--------------------");
for (int[] sampleCase : sampleCases) {
int sampleNum1 = sampleCase[0];
int sampleNum2 = sampleCase[1];
double sampleQuotient1 = (double) sampleNum1 / sampleNum2;
double sampleQuotient2 = (double) sampleNum2 / sampleNum1;
System.out.printf(
"%d / %d = %.6f%n", sampleNum1, sampleNum2, sampleQuotient1);
System.out.printf(
"%d / %d = %.6f%n", sampleNum2, sampleNum1, sampleQuotient2);
}
// begin to calculate
double quotient1 = (double) number1 / number2;
double quotient2 = (double) number2 / number1;
// Display results of user input
System.out.println("------------------Your input---------------------");
System.out.printf("%.2f / %.2f = %.6f%n", number1, number2, quotient1);
System.out.printf("%.2f / %.2f = %.6f%n", number2, number1, quotient2);
}
}
}
}