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.

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****************

importjava.awt.*;importjavax.swing.*;importjava.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.publicclass Temperatures extendsJFrameimplementsActionListener, KeyListener{// Here are the Swing components that we want to access within the// various event functionsprivateJTextField textLowTemperature;// for entry and display of a low temperatureprivateJTextField textHighTemperature;// for entry and display of high temperatureprivateJLabel labelMean;// for display of the average (mean) temperature// And here are two Temperature objects that we'll use in this appprivate 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(newJLabel("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 =newJPanel();
middlePanel.add(newJLabel("High temperature:"));
textHighTemperature =newJTextField("100",4);// Add a KeyListener to the text field
textHighTemperature.addKeyListener(this);
middlePanel.add(textHighTemperature);
middlePanel.add(newJLabel("Low temperature:"));
textLowTemperature =newJTextField("0",4);// Add another KeyListener
textLowTemperature.addKeyListener(this);
middlePanel.add(textLowTemperature);
middlePanel.add(newJLabel("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 =newJLabel("50\u00b0C");
middlePanel.add(labelMean);
add(middlePanel, BorderLayout.CENTER);JPanel bottomPanel =newJPanel();// You make the radio buttons work together by// adding them to a ButtonGroup.ButtonGroup scaleGroup =newButtonGroup();// Here's the first radio button. Use an ActionListener to handle// click events with radio buttons.JRadioButton radioFahrenheit =newJRadioButton("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 =newJRadioButton("Celsius",true);
radioCelsius.addActionListener(this);
radioCelsius.setActionCommand("Celsius");
scaleGroup.add(radioCelsius);
bottomPanel.add(radioCelsius);JRadioButton radioKelvin =newJRadioButton("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.publicvoid 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}elseif(e.getActionCommand().equals("Celsius")){// another static method
Temperature.useCelsius();
redisplay();}elseif(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.publicvoid 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 fieldString 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 doubledouble 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.elseif(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:publicvoid keyPressed(KeyEvent e){}publicvoid 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.privatevoid 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 JLabelprivatevoid showMean(){
Temperature mean = highTemperature.mean(lowTemperature);
labelMean.setText(""+mean);}//The same GUI startup. Copy. Paste. Edit.publicstaticvoid main(String args[]){
javax.swing.SwingUtilities.invokeLater(newRunnable(){publicvoid run(){
Temperatures frame =new Temperatures();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);}});}privatestaticfinallong 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".importjava.text.DecimalFormat;// Celsius = (Fahrenheit - 32) * 5/9// Fahrenheit = Celsius * 9/5 + 32// Kelvin = Celsius + 273.15// Celsius = Kelvin - 273.15publicclass Temperature {// private static: some way to keep track of the current scale: Celsius, Fahrenheit, or KelvinprivatestaticString 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.privatedouble 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.}publicstaticvoid useFahrenheit(){// This sets the currently used scale for ALL instances of the temperature object to Fahrenheit.
temperatureScale ="F";}publicstaticvoid useCelsius(){// This sets the currently used scale for ALL instances of the temperature object to Celsius.
temperatureScale ="C";}publicstaticvoid useKelvin(){// This sets the currently used scale for ALL instances of the temperature object to Kelvin.
temperatureScale ="K";}publicvoid 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}elseif(temperatureScale =="F"){
temperature =(value -32)*5/9.0;//if the temperature scale is Fahrenheit, then convert the value to Celsius.}elseif(temperatureScale =="K"){
temperature =(value -273.15);//if the temperture scale is Kelvin, then convert the value to Celsius.}}publicString 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.}elseif(temperatureScale =="K"){
temperature = temperature +273.15;// Covert from Celsius to Kelvin, if the current scale is Kelvin.}DecimalFormat df =newDecimalFormat("#.##");
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