Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 2 of 2

Thread: Temperature Converting Application

  1. #1
    Junior Member
    Join Date
    Mar 2012
    Posts
    1
    My Mood
    Confused
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Temperature Converting Application

    So the Temperatures application cannot be edited but i have to create a Temperature object. I have a problem with converting my temperatures back to Celsius. And there is a issue with the mean method. There is a lot of code below but the Temperatures.java is just for a reference. The Temperature.java is the code below it, that I am having issues with. Thank you

    *****Temperatures.java****************

    import java.awt.*;
    import javax.swing.*;
    import java.awt.event.*;
     
     
    // For this app, in addition to implementing an ActionListener that will 
    // tell us about button and radio button clicks, we also implement a
    // KeyListener that will tell us about keypress events.
    public class Temperatures extends JFrame
        implements ActionListener, KeyListener
    {
     
        // Here are the Swing components that we want to access within the
        // various event functions
        private JTextField textLowTemperature;  // for entry and display of a low temperature
        private JTextField textHighTemperature; // for entry and display of high temperature
        private JLabel labelMean; // for display of the average (mean) temperature
     
        // And here are two Temperature objects that we'll use in this app
        private Temperature highTemperature;
        private Temperature lowTemperature;
     
     
        // Again, here is where we define what our window looks like and what's inside it. 
        public Temperatures()
        {
            // Set the title bar and size of the window
            setTitle("Temperatures");
            setSize(500,150);
     
            // This time, adding a label to the NORTH (top) of the BorderLayout
            add(new JLabel("Enter the high and low temperatures:"), BorderLayout.NORTH);
     
     
            // The JPanel in the center of the BorderLayout will have two 
            // JTextFields (each preceded by a JLabel), and another JLabel that
            // will be used to display the mean temperature that we compute.
            JPanel middlePanel = new JPanel();
     
            middlePanel.add(new JLabel("High temperature:"));
            textHighTemperature = new JTextField("100",4);
            // Add a KeyListener to the text field
            textHighTemperature.addKeyListener(this);
            middlePanel.add(textHighTemperature);
     
            middlePanel.add(new JLabel("Low temperature:"));
            textLowTemperature = new JTextField("0",4);
            // Add another KeyListener
            textLowTemperature.addKeyListener(this);
            middlePanel.add(textLowTemperature);
     
            middlePanel.add(new JLabel("Mean:"));
            // The Unicode character 00B0 is a degree symbol. To put a special Unicode
            // character in a string, use \\u followed by the hexadecimal value. So
            // here we use \\u00b0 (okay, I had to use \\ to show it to you here to 
            // prevent compiler errors, even though this is within a comment!) 
            // The "C" is at the end because I DO want "C" for Celsius!
            labelMean = new JLabel("50\u00b0C");
            middlePanel.add(labelMean);
     
            add(middlePanel, BorderLayout.CENTER);
     
     
            JPanel bottomPanel = new JPanel();
     
            // You make the radio buttons work together by
            // adding them to a ButtonGroup.
            ButtonGroup scaleGroup = new ButtonGroup();
     
            // Here's the first radio button. Use an ActionListener to handle
            // click events with radio buttons.
            JRadioButton radioFahrenheit = new JRadioButton("Fahrenheit",false);
            radioFahrenheit.addActionListener(this);
            // Since there are multiple radio buttons, set a unique ActionCommand
            // for each.
            radioFahrenheit.setActionCommand("Fahrenheit");
            // Add it to the ButtonGroup so the radio buttons act together in a 
            // group, and add it to the JPanel it displays in our window.
            scaleGroup.add(radioFahrenheit);
            bottomPanel.add(radioFahrenheit);
     
            // Here are the other two radio buttons. Copy above. Paste. Edit.
            JRadioButton radioCelsius = new JRadioButton("Celsius",true);
            radioCelsius.addActionListener(this);
            radioCelsius.setActionCommand("Celsius");
            scaleGroup.add(radioCelsius);
            bottomPanel.add(radioCelsius);
     
            JRadioButton radioKelvin = new JRadioButton("Kelvin",true);
            radioKelvin.addActionListener(this);
            radioKelvin.setActionCommand("Kelvin");
            scaleGroup.add(radioKelvin);
            bottomPanel.add(radioKelvin);
     
            // Add the radio button JPanel to the bottom of the window's BorderLayout
            add(bottomPanel, BorderLayout.SOUTH);
     
            // Now that the components for our window are all created, initialize 
            // other variables. Here we create two Temperature instances with
            // starting values 100 and 0 degrees Celsius. The default constructor will
            // use 0 degrees Celsius.
            highTemperature = new Temperature(100.0);
            lowTemperature = new Temperature();
        }
     
     
        // These are the ActionListener events for the clicks on the 
        // radio buttons.
        public void actionPerformed(ActionEvent e)
        {
            if (e.getActionCommand().equals("Fahrenheit"))
            { 
                // This tells ALL our Temperature instances to use Fahrenheit
                // as the current input and output scale. This is a static 
                // method, and the flag you use to indicate the currently-used
                // scale should also be static so that it applies to ALL 
                // temperature instances.
                Temperature.useFahrenheit();
                redisplay(); // see this method below
            }
            else if (e.getActionCommand().equals("Celsius"))
            {    
                // another static method
                Temperature.useCelsius();
                redisplay();
            }
            else if (e.getActionCommand().equals("Kelvin"))
            {    
                // and one more static method
                Temperature.useKelvin();
                redisplay();
            }
        }
     
        // KeyListener tells us about three Key Events, and if we implement
        // a KeyListener we MUST provide methods to handle all three. Here 
        // we're acting on keyReleased because we want to look at the text
        // fields AFTER the new keypress entered into it.
        public void keyReleased(KeyEvent e) 
        {
            // To distinguish between which JTextField generated the 
            // key event, we can use e.getSource(). textHighTemperature is
            // one of the two JTextFields to which we attached KeyListeners.
            if (e.getSource() == textHighTemperature)
            {
                // After the keypress, get the content of the text field
                String s = textHighTemperature.getText();
                // We just want the numeric value, so we have to remove the
                // degree symbol and C, F, or K if they are there. Use some
                // String methods to do so.
                // First get the location of the degree symbol, IF there is one.
                int degreeSymbol = s.indexOf('\u00b0');
                // -1 if not there.
                if (degreeSymbol>=0)
                    // if it was there, extract only the characters before it
                    s = s.substring(0,degreeSymbol);
                // and convert those numerals (we hope!) to type double
                double value = Double.parseDouble(s);
                // use the Temperature object's set method!
                highTemperature.set(value);
                showMean(); // see this method below.
            }    
            // Do the same for the other text field. The "if" here is really
            // redundant, since there is only this one other possibility.
            else if (e.getSource() == textLowTemperature)
            {
                String s = textLowTemperature.getText();
                int degreeSymbol = s.indexOf('\u00b0');
                if (degreeSymbol>=0)
                    s = s.substring(0,degreeSymbol);
                double value = Double.parseDouble(s);
                lowTemperature.set(value);
                showMean();
            }    
        }
     
        // Three keyListener methods are required when you "implement KeyListener"
        // These are the other two that are required, but we don't use them.
        // So these are just "stubs" with no code:
        public void keyPressed(KeyEvent e) {}
        public void keyTyped(KeyEvent e){}
        // The sequence of key events is keyPressed -> keyTyped -> keyReleased
        // keyTyped lets us check the key code before it is actually put into
        // the text field.
     
        // Re-display the contents of the text boxes using the current Temperature
        // scale, then re-compute and display the mean temperature.
        private void redisplay()
        {
            textHighTemperature.setText(""+highTemperature);
            textLowTemperature.setText(""+lowTemperature);
            showMean();
        }
     
        // Re-compute the mean temperature using the Temperature object's
        // "mean" method, then display the result in the output JLabel
        private void showMean()
        {
            Temperature mean = highTemperature.mean(lowTemperature);
            labelMean.setText(""+mean);
        }
     
     
     
        //The same GUI startup. Copy. Paste. Edit.
        public static void main(String args[])
        {
            javax.swing.SwingUtilities.invokeLater(new Runnable() 
            { 
                public void run() 
                { 
                    Temperatures frame = new Temperatures();
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.setVisible(true);
                } 
            });
        }
         private static final long serialVersionUID = 1L;
     
    }

    *********Temperature.java*******************
    // NEEDED FOR Temperature OBJECT:
    // Two constructors:
    //    The default constructor initializes the Temperature instance to 0 degrees Celsius
    //    The overloaded constructor receives a double. It initializes the instance to 
    //       that value IN THE CURRENT SCALE.
    //    See the last two instructions in the above app's constructor for examples of usage.
    //
    // public static methods useCelsius(), useFahrenheit(), and useKelvin(). These set the 
    //    currently used scale for ALL instances of the temperature object. See the 
    //    actionPerformed method in the above app for example of usage.
    //
    // private static: some way to keep track of the current scale: Celsius, Fahrenheit, or Kelvin
    //
    // private: a property to keep track of the currently stored temperature. 
    //     Hint, suggestion, STRONG suggestion: Choose one scale to use internally for storing
    //     the temperature. Make conversions to the other scales only if needed in input/output
    //     operations from your object.
    //
    // public method .set(double) receives a numeric value and stores that as the current 
    //     temperature USING THE CURRENT SCALE. If your internal scale is different, make sure
    //     you convert. For example, if you store your temperatures internally as Celsius, but
    //     the current scale selected is Fahrenheit, the value in .set is Fahrenheit and you
    //     should convert it to Celsius before storing it. See usage of .set() in the 
    //     keyReleased method in the above app.
    //
    // public method .toString() returns a string with the temperature IN THE CURRENT SCALE,
    //     followed by the degree symbol and C, F, or K depending on the current scale.
    //     A conversion will be needed if the current scale is not what you use internally.
    //     The toString method is used implicitly in the "redisplay" method shown above.
    //
    // public method .mean() receives another Temperature instance and returns a Temperature
    //     instance as the answer. Example: Temperature three = one.mean(two);
    //     "one" and "two" are both instances of Temperature. The mean method adds the two
    //     internal values together and divides by 2. It creates an "answer" Temperature and
    //     sets its internal value to the result, and then returns "answer".
     
     
     
    import java.text.DecimalFormat;
     
    // Celsius = (Fahrenheit - 32) * 5/9
    // Fahrenheit = Celsius * 9/5 + 32
    // Kelvin = Celsius + 273.15
    // Celsius = Kelvin - 273.15
     
     
    public class Temperature {
     
    	// private static: some way to keep track of the current scale: Celsius, Fahrenheit, or Kelvin
    	private static String temperatureScale;
     
    	// private: a property to keep track of the currently stored temperature. Choose one scale to use internally for storing
    	// the temperature. Make conversions to the other scales only if needed in input/output operations from your object.
    	private double temperature;
     
    		public Temperature() {
    		//This is the default constructor and it initializes the Temperature instance to 0 degrees Celsius(Internal Scale)	
     
    		temperature = 0.0;
    		// temperature instance is initialized to 0 degress Celsius
     
    		temperatureScale = "C";
    		// the internal scale is set to Celsius
    	}
     
    	public Temperature(double temp) {
    		//This constructor receives a double. It initializes the instance to that value IN THE CURRENT SCALE.
     
    		temperature = temp;
    		// initializes the instance to the double in the current scale.
    	}
     
    	public static void useFahrenheit() {
    		// This sets the currently used scale for ALL instances of the temperature object to Fahrenheit.
    		temperatureScale = "F";
    	}
     
    	public static void useCelsius() {
    		// This sets the currently used scale for ALL instances of the temperature object to Celsius.
    		temperatureScale = "C";
    	}
     
    	public static void useKelvin() {
    		// This sets the currently used scale for ALL instances of the temperature object to Kelvin.	
    		temperatureScale = "K";
    	}
     
    	public void set(double value) {
    		//This method receives a numeric value and stores it as the current temperature USING THE CURRENT SCALE. 
    		//If your internal scale is different, convert.	
     
    		if (temperatureScale == "C"){
    			temperature = value;
    			//if the temperature scale is Celsius, no need to convert
    		}
    		else if(temperatureScale == "F"){
    			temperature = (value - 32) * 5/9.0;
    			//if the temperature scale is Fahrenheit, then convert the value to Celsius.
     
    		}else if (temperatureScale == "K"){
    			temperature = (value - 273.15);
    			//if the temperture scale is Kelvin, then convert the value to Celsius.
    		}
     
    	}
     
    	public String toString(){
    		//This method returns a string with the temperature IN THE CURRENT SCALE,
    		//followed by the degree symbol and C, F, or K depending on the current scale.
    		//A conversion will be needed if the current scale is not what you use internally.
     
    		String temperatureString;
     
    		if(temperatureScale == "F"){
    			temperature = temperature * 9/5.0 + 32;
    			// Covert from Celsius to Fahrenheit, if the current scale is Fahrenheit.
     
    		}else if (temperatureScale == "K"){
    			temperature = temperature + 273.15;
    			// Covert from Celsius to Kelvin, if the current scale is Kelvin.
     
    		}
    		DecimalFormat df = new DecimalFormat("#.##");
     
    		temperatureString = df.format(temperature) + '\u00b0' + temperatureScale;
    		// string with the temperature, degree symbol, and letter for scale.
     
    		return temperatureString;
    	}
     
    	public Temperature mean(Temperature otherTemperature) {
    		//This method receives another Temperature instance and returns a Temperature instance as the answer. 
    		//It adds the two internal values together and divides by 2. 
    		//It creates an "answer" Temperature and sets its internal value to the result, and then returns "answer".
     
    		double average = (temperature + otherTemperature.temperature) /2.0;
    		// Create Temperature mean and find the mean of the two Temperature instances.
    		Temperature mean = new Temperature (average);
     
    		return mean;
    	}	
    }
    Last edited by helloworld922; March 3rd, 2012 at 07:44 PM. Reason: please use [code] tags


  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    21,935
    Thanks
    55
    Thanked 2,353 Times in 2,324 Posts

    Default Re: Temperature Converting Application

    Please post you list of questions.
    If you are getting errors, copy and paste them here.

    Please Edit your post and wrap your code with[code=java]<YOUR CODE HERE>[/code] to get highlighting

Similar Threads

  1. Temperature Table Celsius and Fahrenheit
    By Krodfish in forum Loops & Control Statements
    Replies: 2
    Last Post: February 2nd, 2012, 10:06 PM
  2. (Beginner) Hopelessly lost on Temperature converting (C to F, F to C)
    By skw4712 in forum What's Wrong With My Code?
    Replies: 13
    Last Post: July 18th, 2011, 08:34 PM
  3. NEED HELP WITH TEMPERATURE
    By Dracer in forum AWT / Java Swing
    Replies: 5
    Last Post: December 11th, 2010, 03:12 PM
  4. Replies: 0
    Last Post: December 3rd, 2009, 04:43 PM
  5. Converting temperature program
    By ixjaybeexi in forum What's Wrong With My Code?
    Replies: 3
    Last Post: October 20th, 2009, 08:27 PM