I'm a tad confused on a homework assignment. I'm supposed to write a program that displays a table of the Celsius temperatures 0 through 20 and their Fahrenheit equivalents. I got the loop to work just fine, but I'm supposed to display the results of the loop in a TextArea box. The teacher went over it once in class, but I'm having trouble grasping it.

Here's what I wrote so far:

package celsiustofahrenheit;

import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class CelsiusToFahrenheit { 
    public static void main(String[] args) 
    { 

        JOptionPane.showMessageDialog(null, "This program will display a table of Celsius "
                + "temperatures 0 through 20 and their Fahrenheit equivalents.");

     int Fahrenheit = 0;
     int Celcius = 0;

      JTextArea text;
      JScrollPane pane;

      String input = "";

        while (Celcius<20)
      {
      Fahrenheit = Celcius*9/5+32;
      Celcius++;   
      JOptionPane.showMessageDialog(null,  "Celcius = " + Celcius + "");
      JOptionPane.showMessageDialog(null, "Fahrenheit = " + Fahrenheit + "");
      }
      text = new JTextArea(5,15);

      text.setText(input);
      pane = new JScrollPane(text);
      JOptionPane.showMessageDialog(null, pane);
    }  
}

I would like to know what I'm doing wrong. Thank you.

You're using JOptionPane.showMessageDialog inside the loop, which is why you'll get a lot of dialog windows. The input String you defined is not being filled, so it stays blank. Replace the method calls inside the loop and store the information in input instead.

Secondly, by using the integer type for fahrenheit and celsius the values are being rounded and thus you're losing accuracy. Use a double (for both) instead.

Also, you're increasing Celsius by one before printing, resulting in a wrong output for celsius.

FYI, the variable names Celsius and Fahrenheit, by convention, should not start with a capital letter. If you're using an IDE you can easily rename them all at once by right clicking on them, selecting "refactor" and then "rename".

JTextArea has an append(String s) method that you call to add text to the end of whatever is currently being displayed in the text area (which starts out empty).

So before your loop, create a text area and add it to a JFrame that's visible on the screen. Use a scroll pane if you want - in which case add the scrioll pane to your JFrame
Then inside your loop (lines 26.27 above), instead of showing that text in dialogs, append it to your JTextArea.

(plus see Traevel's good advice above)

This article has been dead for over six months. Start a new discussion instead.