final and Constants

Lab Java Beginner 10 points

Create a utility class Units with public static final double KM_PER_MILE = 1.609344, a private constructor and static methods toKm and toMiles. Read km X or mi X lines and print the conversion with 3 decimals.

Input

n, then n lines.

Output

n lines.

Example

Input

2
mi 26.2
km 5

Output

42.165 km
3.107 mi
Sample input available Sample output available
Editor
Java

Hints

A private constructor stops anyone creating Units objects.

final on a class stops subclassing.

Solution explanation

Utility classes like Math use exactly this pattern.

Show solution
import java.util.Scanner;

final class Units {
    public static final double KM_PER_MILE = 1.609344;

    private Units() {
    }

    static double toKm(double miles) {
        return miles * KM_PER_MILE;
    }

    static double toMiles(double km) {
        return km / KM_PER_MILE;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            String unit = sc.next();
            double value = sc.nextDouble();
            if (unit.equals("mi")) {
                System.out.printf("%.3f km%n", Units.toKm(value));
            } else {
                System.out.printf("%.3f mi%n", Units.toMiles(value));
            }
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD