Length Converter

// LC means Length Converter , so this file named Lc.java

import java.util.Scanner;

public class Lc {

    public static void main(String[] args) {
        // define the conversion factor
        final int INCHES_PER_YARD = 36;
        final int INCHES_PER_FOOT = 12;
        // create new scan to obtain user's input
        try (Scanner scan = new Scanner(System.in)) {
            while (true) {
                System.out.println("Please enter a number in inches or 'bye' to quit. ");
                if (scan.hasNext("bye")) {
                    System.out.println("Goodbye!");
                    break;
                }
                // deal with valid input
                if (scan.hasNextInt()) {
                    int inches = scan.nextInt();
                    // Convert between inches and yards
                    int yards = inches / INCHES_PER_YARD;
                    int remainingInchesAfterYards = inches % INCHES_PER_YARD;
                    // Convert between inches and feet
                    int feet = remainingInchesAfterYards / INCHES_PER_FOOT;
                    int remainingInches = remainingInchesAfterYards % INCHES_PER_FOOT;
                    int[] sampleInches = {0, 12, 36, 49, 99};
                    // Display examples
                    System.out.println("-------------------------------------------------");
                    System.out.println("1 yard = 3 feet, 1 foot = 12 inches;");
                    System.out.println("------------------For example--------------------");
                    for (int sampleInch : sampleInches) {
                        int sampleYards = sampleInch / INCHES_PER_YARD;
                        int sampleRemainingInchesAfterYards = sampleInch % INCHES_PER_YARD;
                        int sampleFeet = sampleRemainingInchesAfterYards / INCHES_PER_FOOT;
                        int sampleRemainingInches = sampleRemainingInchesAfterYards % INCHES_PER_FOOT;
                        System.out.printf("%d inches equal to %d yards, %d feet, and %d inches .%n", sampleInch,
                                sampleYards, sampleFeet, sampleRemainingInches);
                    }
                    // Display the results of user input
                    System.out.println("------------------Your input---------------------");
                    System.out.println(
                            String.format("%d inches equal to about %d yards, %d feet, and %d inches.", inches,
                                    yards, feet, remainingInches));
                    System.out.println("-------------------------------------------------");
                } else { // deal with invalid input
                    System.out.println("Invalid input. Please enter again!");
                    scan.next();
                }
            }
        }
    }
}

 

Scroll to Top