A measure conversion tool using Java
Today we will learn about how to create a measure conversion tool using Java.
The problem has been solved using hashmaps for the following reasons:
- Inserting elements in a hashmap takes O(1) average time complexity.
- It is also very efficient for data retrieval taking O(1) average time complexity.
Java Code:
import java.util.HashMap; import java.util.Map; import java.util.Scanner; public class Measures{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); Map<String, Double> convert = new HashMap<String,Double>(); convert.put("km to miles", 0.621371); convert.put("km to meters",1000.0); convert.put("miles to km", 1.60935); convert.put("miles to meters",1609.35); convert.put("meters to cm",100.0); convert.put("meters to mm", 1000.0); convert.put("foot to inch", 12.0); convert.put("celsius to fahrenheit",33.8); convert.put("celsius to kelvin",274.15); System.out.println("Enter the value to convert:"); double value = sc.nextDouble(); sc.nextLine(); System.out.println("Enter the conversion type (e.g.,km to miles,km to meters,miles to km,miles to meters,meters to cm,meters to mm,foot to inch,celsius to fahrenheit,celsius to kelvin):"); String input= sc.nextLine().toLowerCase(); if (convert.containsKey(input)) { double result = value * convert.get(input); System.out.println("Converted value: " + result); } else { System.out.println("Invalid conversion type."); } } }
Explanation:
HashMap and Map classes have been imported from the java.util package to use map data structure.
Since we have to take user input, we do so with the help of Scanner class. To use the Scanner class, we import the java.util package in our program.
An object sc of Scanner class has been created to take input from the user.
Map<String, Double> convert = new HashMap<String,Double>(); //A HashMap called convert is created which maps strings(key) to double values(value).
Elements are then added to the map using the put method.
After taking the value as input,we write sc.nextLine() to consume the newline character left by nextDouble().This is done to prevent issues when reading the next line of input.
The conversion type is then taken as input from the user which is then converted to lowercase.
if (convert.containsKey(input)) //this line checks if the key is present in the convert map
If yes, the corresponding value to the key is multiplied with the user input value. Else it prints that the conversion type is invalid.
Output:
Enter the value to convert: 23 Enter the conversion type (e.g.,km to miles,km to meters,miles to km,miles to meters,meters to cm,meters to mm,foot to inch,celsius to fahrenheit,celsius to kelvin): foot to inch Converted value: 276.0
Also learn: Convert double number to 3 decimal places number in Java
Leave a Reply