Distance Converter

// DC means Distance Converter , so this file named Dc.java

import java.util.Scanner;

public class Dc {

    public static void main(String[] args) {
        // define the conversion factor
        final double CONVERSION_FACTOR = 1.60935;

        // create new scan to obtain user's input
        try (Scanner scan = new Scanner(System.in)) {
            while (true) {
                // Hints user to enter miles
                System.out.println("Please enter a number in miles or 'bye' to quit. ");
                if (scan.hasNext("bye")) {
                    System.out.println("Goodbye!");
                    break;
                }
                // got number and begin to calculate
                if (scan.hasNextDouble()) {
                    double miles = scan.nextDouble();
                    double kilometers = miles * CONVERSION_FACTOR;
                    double[] samplesMiles = {0, 0.5, 1, 50, 123.45};
                    // Display example data
                    System.out.println("-------------------------------------------------");
                    System.out.println(" 1 mile ≈ 1.06935 km;");
                    System.out.println("------------------For example--------------------");
                    for (double sampleMile : samplesMiles) {
                        double sampleKilometers = sampleMile * CONVERSION_FACTOR;
                        System.out.printf("%.2f miles equal to about %.2f km.%n", sampleMile, sampleKilometers);
                    }
                    // Display results of user input
                    System.out.println("------------------Your input---------------------");
                    System.out.println(
                            String.format("%.2f miles equal to about %.2f km.", miles, kilometers));
                    System.out.println("-------------------------------------------------");
                } else {
                    System.out.println("Invalid input. Please enter again!");
                    scan.next();
                }
            }
        }
    }
}

 

Scroll to Top