|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
Weight Converter, Pound to Kilogram, Ounce to Kilogram
This example shows how to take input from the user and convert pound to Kilogram and also how to convert Ounce to Kilogram. The user should first enter a number in pound. The program makes the conversion to Kilogram and prints out the result. Next the user is asked to enter a number in ounce. The program makes the conversion to Kilogram and prints out the result. It uses a BufferedReader and InputStreamReader to collect the input from the user. |
package weightconverter; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; /** * * @author www.javadb.com */ public class Main { public void start() throws IOException { boolean inputOk = false; BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); //1 ounce = 0.0283495231 kilograms //1 pound = 0.45359237 kilograms double pound = 0; while (!inputOk) { System.out.println("Enter number in pound:"); try { pound = Double.parseDouble(reader.readLine().trim()); inputOk = true; } catch (NumberFormatException e) { System.out.println("Invalid number, try again."); } } System.out.println(pound + " pound is equal to " + getPoundToKg(pound) + " kgs & " + getPoundToGrams(pound) + " grams"); inputOk = false; double ounce = 0; while (!inputOk) { System.out.println("Enter number in ounce:"); try { ounce = Double.parseDouble(reader.readLine().trim()); inputOk = true; } catch (NumberFormatException e) { System.out.println("Invalid number, try again."); } } System.out.println(ounce + " ounce is equal to " + getOunceToKg(ounce) + " kgs & " + getOunceToGrams(ounce) + " grams"); } private int getPoundToKg(double pound) { double kg = pound * 0.45359237; return (int)Math.floor(kg); } private double getPoundToGrams(double pound) { double kg = pound * 0.45359237; return (kg - getPoundToKg(pound)) * 1000; } private int getOunceToKg(double ounce) { double kg = ounce * 0.0283495231; return (int)Math.floor(kg); } private double getOunceToGrams(double ounce) { double kg = ounce * 0.0283495231; return (kg - getOunceToKg(ounce)) * 1000; } /** * @param args the command line arguments */ public static void main(String[] args) { try { new Main().start(); } catch (IOException ex) { ex.printStackTrace(); } } } |
This is what the output could look like when the above class is executed: |
Enter number in pound: 100 100.0 pound is equal to 45 kgs & 359.23700000000025 grams Enter number in ounce: 100 100.0 ounce is equal to 2 kgs & 834.9523099999998 grams |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
