Here is the code for the MilesToKilometersConversion class
The code is also available at Github
package com.spconger.MilesToKilometers; public class MilesToKilometersConversion { /** * This class takes miles as an argument * and converts it to kilometers * 7/1/2013 */ //private fields private double miles; private double kilometers; //private constant private final double CONVERSIONFACTOR=1.6; //empty constructor public MilesToKilometersConversion(){ setMiles(0); setKilometers(0); } //constructor that takes miles as a parameter public MilesToKilometersConversion(double miles){ setMiles(miles); setKilometers(0); } //public sets and gets for private fields public double getMiles() { return miles; } public void setMiles(double miles) { this.miles = miles; } public double getKilometers() { return kilometers; } public void setKilometers(double kilometers) { this.kilometers = kilometers; } //public method to convert miles to kilometers public void convertToKilometers(){ setKilometers(getMiles() * CONVERSIONFACTOR); } }
Here is the Program
package com.spconger.MilesToKilometers; import acm.program.*; import acm.graphics.*; import acm.io.IODialog;; @SuppressWarnings("serial") public class Program extends GraphicsProgram{ /** * this class gets the Miles from the user * with a dialog box and passes it to the * MilesToKilometersConversion class * which does the conversion and passes the * kilometers value back to a label * 7/1/2013 */ public void run(){ setSize(400,500); //create a dialog box IODialog dialog = new IODialog(); //get the value from the dialog double miles = dialog.readDouble("Please enter the miles"); //initialize the class and pass the miles //in the constructor MilesToKilometersConversion mToK= new MilesToKilometersConversion(miles); //call the conversion method mToK.convertToKilometers(); //Display the results in a label GLabel label=new GLabel(miles + " equals " +mToK.getKilometers() + " Kilometers", 50,60); //add the label to the graphics program add(label); } }
No comments:
Post a Comment