Tuesday, July 28, 2009

Syntax error in JAVA (convert Farhenheit to Centigrade exercise)?

Self-teaching is frustrating.


I wrote a script to convert Fahrenheit to Centigrade. I reduced my errors (about 24) down to 1. When I 'fixed' that, I got 4 new ones.


I think my errors are here:


Temp = Double.parseDouble(FahrenheitString);


Centigrade = 5/9*(FahrenheitString - 32);





Here's the script:


import javax.swing.JOptionPane;


public class TEST


{


public static void main(String[] args)


{


String FahrenheitString;


double Fahrenheit;


double Centigrade;





FahrenheitString = JOptionPane.showInputDialog(null, "Enter the Temperature in Fahrenheit ", "Temperature in FAHRENHEIT", JOptionPane.INFORMATION_MESSAGE);





Temp = Double.parseDouble(FahrenheitString);


Centigrade = 5/9*(FahrenheitString - 32);





JOptionPane.showMessageDialog (null, "The temperature in CENTIGRADES is "+ C=5/9*(Fahrenheit - 32));


System.exit(0);


}


}





Any help/guidance or SOLUTIONS are greatly appreciated (before I pull my hair out - lol)

Syntax error in JAVA (convert Farhenheit to Centigrade exercise)?
a few suggestions:


*don't declare any variables before you actually need them


*use the typical naming conventions (Test instead of TEST, fahrenheitString instead of FahrenheitString)


*no need to put System.exit(0) at the end, since the program will end anyway when it reaches the end of the main method


*the "5/9" part will produce 0 because it is evaluated as an integer division, so change one of the operands to a double: 5D/9 (or 5.0/9)





A working version:





import javax.swing.JOptionPane;





public class Test {





public static void main(String[] args) {


String tempFString = JOptionPane.showInputDialog(null, "Enter the temperature in °F");


double tempF = Double.valueOf(tempFString);


double tempC = 5D/9*(tempF-32);


JOptionPane.showMessageDialog (null, "The temperature in °C is "+tempC);


}





}
Reply:It seems to me that the code you posted:





Temp = Double.parseDouble(FahrenheitString);


Centigrade = 5/9*(FahrenheitString - 32);





Needs to be:





Temp = Double.parseDouble(FahrenheitString);


Centigrade = 5/9*(Temp - 32);





Hopefully that is the problem.


No comments:

Post a Comment