Temperature Conversion
Hi to all!
It's my first post here.
I just started my very first java class, and I have problem with my assignment.
I have to write a program that accepts an integer # followed by a space and one letter, C or F. It should then convert number to opposite degrees (C or F).
Example of output:
Enter temperature: 35 F
Temperature in C is: 1.6
I managed to write the code, but I have a feeling that there is easier way to do this (while loop?).
Also, I'm getting following error when I input letter other than C or F, shouldn't it go straight to "else" in this case?
Enter temperature: 35 D
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String ind
ex out of range: 4
at java.lang.String.charAt(Unknown Source)
at TempConversion.main(TempConversion.java:57)
import java.util.Scanner; // Needed for the scanner class
public class TempConversion
public static void main(String[] args)
String temperature; // To hold user's input
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter temperature: ");
temperature = keyboard.nextLine();
if (temperature.charAt(1) == ' ' && temperature.charAt(2) == 'F')
String temp1 = temperature.substring(0,1);
double temp1d = Double.parseDouble(temp1);
System.out.println("Temp1 F to C: "+(5.0/9.0)*(temp1d-32.0));
else if (temperature.charAt(1) == ' ' && temperature.charAt(2) == 'C')
String temp1 = temperature.substring(0,1);
double temp1d = Double.parseDouble(temp1);
System.out.println("Temp1 C to F: "+(((9.0/5.0)*temp1d)+32.0));
else if (temperature.charAt(2) == ' ' && temperature.charAt(3) == 'F')
String temp2 = temperature.substring(0,2);
double temp2d = Double.parseDouble(temp2);
System.out.println("Temp2 F to C: "+(5.0/9.0)*(temp2d-32.0));
else if (temperature.charAt(2) == ' ' && temperature.charAt(3) == 'C')
String temp2 = temperature.substring(0,2);
double temp2d = Double.parseDouble(temp2);
System.out.println("Temp1 C to F: "+(((9.0/5.0)*temp2d)+32.0));
else if (temperature.charAt(3) == ' ' && temperature.charAt(4) == 'F')
String temp3 = temperature.substring(0,3);
double temp3d = Double.parseDouble(temp3);
System.out.println("Temp3 F to C: "+(5.0/9.0)*(temp3d-32.0));
else if (temperature.charAt(3) == ' ' && temperature.charAt(4) == 'C')
String temp3 = temperature.substring(0,3);
double temp3d = Double.parseDouble(temp3);
System.out.println("Temp1 C to F: "+(((9.0/5.0)*temp3d)+32.0));
else if (temperature.charAt(4) == ' ' && temperature.charAt(5) == 'F')
String temp4 = temperature.substring(0,4);
double temp4d = Double.parseDouble(temp4);
System.out.println("Temp4 F to C: "+(5.0/9.0)*(temp4d-32.0));
else if (temperature.charAt(4) == ' ' && temperature.charAt(5) == 'C')
String temp4 = temperature.substring(0,4);
double temp4d = Double.parseDouble(temp4);
System.out.println("Temp1 C to F: "+(((9.0/5.0)*temp4d)+32.0));
else
System.out.println("Input format is invalid.");
}
stdunbar wrote:
Can I suggest two things: (1) use the trim() method (http://java.sun.com/javase/6/docs/api/java/lang/String.html#trim%28%29) to not care how many spaces are before or after the String you got from nextLine() and (2) use split (http://java.sun.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29) to then pull apart the String into the individual pieces. You can then examine the resulting String[] for what you expect to find.
Edited by: stdunbar on Nov 23, 2009 12:26 PM - these are the worst forums in the world to provide useful links with[trim method link|http://java.sun.com/javase/6/docs/api/java/lang/String.html#trim%28%29]
[split method link|http://java.sun.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29]
Or in bare form...
[http://java.sun.com/javase/6/docs/api/java/lang/String.html#trim%28%29]
[http://java.sun.com/javase/6/docs/api/java/lang/String.html#split%28java.lang.String%29]
Although I still think Scanner.nextInt() followed by next() or nextLine() is simpler.
Similar Messages
-
Another question need u all guy help.I currently using K-type thermocoupler for my project using usb 6008.Does the voltage to temperature conversation require in usb 6008 using daqmx 8.5? what is DAQ TEDS function use ? is it help us to convert?
You will need to factor the voltage per degrees C to get to reading in degrees, this is 10mv per degree V for the device mentioned in the post you previously made
http://forums.ni.com/ni/board/message?board.id=170&message.id=246200#M246200
TEDS - Transducer Electronic Data Sheet
A video about TEDS
http://digital.ni.com/demo.nsf/websearch/8e55de8fe6b5702686256e7c007a47b4?opendocument -
"RTD Voltage to temperature conversion" for temperatures below 0 degrees
NI gives us a conversion VI for temperatures above 0 degrees Celsius. I need a converter also for negative temperatures.
Where can I find such a VI or a method ?Labviewguru and Filipe:
I found the following rather excellent reference on line as a PDF by
searching RTD+NIST+equation at:
http://www.data-acq.co.uk/pdf/CHAP-4.pdf
It has the NIST polynomial equations and technical descriptions for
various types of thermocouples and RTDs. I think it is just what you
are looking for.
You'll just have to slap them into a LabVIEW equation box and that
should be that.
Douglas De Clue
[email protected]
Labviewguru wrote in message news:<[email protected]>...
> Filipe,
>
> Gosh, I was interested in this one, and kinda curious myself why you
> couldn't convert temperatures below 0degC. I looked up RTDs in the
> Omega Catalog, and sure enough, they
go to at least -200degC.
>
> Would National Instruments be interested in a new algorithm that is
> capable of converting all temperatures? If so, I'll do the legwork,
> find the correct algorithm, and program it up. -
Applescript temperature conversion problem
Hi All,
I am not very experienced at applescript, but am using it to help me convert degrees F to degrees C as part of a home automation system
I have two variables in the system, Outside_F which is the temperature measured by a sensor, the second Outside_C is the result I want to use in a display in centigrade
The below script has worked well, converting the temperature with one decimal place such as 12.3, but now the the outside temperature has dropped due to the time of year so that the result in Outside_C becomes less than 10 I get results like 9.699999999999999 from a Outside_F input of 49.5 with far too many decimal places
set test_temp to value of variable "Outside_F"
set value of variable "Outside_C" to ((round ((test_temp - 32) * 5 / 9) * 10) / 10)
Can one of you bright sparks tell me where I am going wrong ?Hi,
The result of ((round ((49.5 - 32) * 5 / 9) * 10) / 10) is correct, but it seems that your home automation system does not display the number properly.
Try this, it convert the number to string:
set value of variable "Outside_C" to ((round ((test_temp - 32) * 5 / 9) * 10) / 10) as string -
Please help with my Temperature Conversion application
here's my code that compiles OK:
BUT, I want the application to return a value of type int, not float, how do I do this, and why?
thanks
public class TemperateConversion {
public static void main (String [] args) {
double a;
double b;
int C=100;
int F=212;
a = (double)5./9. * (F-32.0);
b = (double)9./5. * C + 32.0;
System.out.println (b + " degrees Fahrenheit is equal to " + a + " Celsius");
System.out.println (a + " degrees Celsius is equal to " + b + " Fahrenheit");hey, this can be done easily by casting the double to int
public class TemperatureConversion {
public static void main (String [] args) {
double a;
double b;
int C=100;
int F=212;
a = (double)5./9. * (F-32.0);
b = (double)9./5. * C + 32.0;
System.out.println (b + " degrees Fahrenheit is equal to " + (int)a + " Celsius");
System.out.println (a + " degrees Celsius is equal to " + (int)b + " Fahrenheit"); -
Temperature conversion not working can someone help me.
import java.awt.Graphics; // program uses class Graphics
import javax.swing.JApplet; // program uses class JApplet
import javax.swing.JOptionPane;
public class Temp1 extends JApplet
// draw text on applet's background
public void paint( Graphics g )
// call superclass version of method paint
super.paint( g );
int cels;
for (int fahr = 0; fahr <= 212; fahr++ )
cels = 5.0 / 9.0 * (fahr - 32);
System.out.printf( "%df\n", cels);
g.drawString( "Is then converted to" + cels + "degrees Celsius", 25, 25 );
} // end method paint
} // end class WelcomeApplet
it does give me one error its says possible loss of precision on line 15, the cels = 5.0 / 9.0 * (fahr - 32); lineYou're basically doing this:
int i = 1.5;Obviously, you can't put 1.5 into an int, so it will get truncated down to 1. However, the compiler is forcing you to either fix it or tell it that you really want to truncate the double to an int.
double d = 1.5;
OR
int i = (int)1.5; -
Does j2sdk1.4.1 have any conversion methods built in. The only ones I know about are, for example, Long.toBinaryString, Long.toOctalString, and Long.toHexString.
Is there any support for converting from say from binary to decimal, or from hex to octal? Also, is there any other methods, like perhaps a simple temperature conversion method?
I searched the api's for "convert" and found nothing, (one find, had to do with colors though).
Thanks - I just dont know the docs well enough.Look at the documentation for the Integer and Long classes.
http://java.sun.com/j2se/1.3/docs/api/java/lang/Integer.html
http://java.sun.com/j2se/1.3/docs/api/java/lang/Long.html
parseInt(String s, int radix)
Parses the string argument as a signed integer in the radix specified by the second argument
toXXXString(int i)
Creates a string representation of the integer argument as an unsigned integer in base XXX -
New semester, new temp conversions
I haven't been part of the Java community long but I have noticed something; every semester at just about the same time are the same questions about the same problems. Temperature conversions, airports, etc...
For some reason I believe that when you sign up you had something to agree to that you would attempt to search the forums first...seems not many people listen.
Vagabon(d)I haven't been part of the Java community long but I
have noticed something; every semester at just about
the same time are the same questions about the same
problems. Temperature conversions, airports, etc...You know how that saying goes. "IF aholes could fly this place would be an airport".
>
For some reason I believe that when you sign up you
had something to agree to that you would attempt to
search the forums first...seems not many people
listen.
Vagabon(d) -
Error while using LabVIEW 8.2.1 Dll from Visual C++ 6.0
I am getting an error while using a LabVIEW 8.2.1 dll from Visual C++ 6.0 application. This is what I am doing:
1) Created a dll using LabVIEW 8.2.1 (I used a tutorial from NI knowledge base: "Creating DLLs from 6.0i". It is a temperature conversion VI; input DegreeF and get DegreeC out). Instead of LabVIEW 6.0i, I used 8.2.1. It created the dll Convert_Temp.dll successfully.
2) Then I created a Visual C++ 6.0 application (used a tutorial from NI knowledge base: "Calling a DLL from Microsoft Visual C++ that was Generated by LabVIEW 6i). I could build the project and create an executable application F_To_C.exe.
3) Then copied the LabVIEW dll Convert_Temp.dll into the folder where F_To_C.exe resides. Using windows explorer, went into that folder, and executed the application. I got the following error:
System Error 998 while loading the LabVIEW run-time engine (C:\Program Files\National Instruments\Shared\LabVIEW Run-Time\8.2\lvrt.dll).
Convert_Temp requires a version 8.2.1 (or compatible) LabVIEW Run-Time Engine. Please contact the vendor of Convert_Temp to correct this problem.
I checked the folder: C:\Program Files\National Instruments\Shared\LabVIEW Run-Time\8.2\. It has the file lvrt.dll.
So why am I getting this error?
GKBsounds like you need to install the LabVIEW 8.2.1 runtime. Not the 8.2 runtime engine.
Paul <--Always Learning!!!
sense and simplicity.
Browse my sample VIs? -
Error in Invoking External Web Service in BPEL
Hello,
I have a Temperature Conversion Web Service deployed on an external server.
I want to invoke this Web Service in my BPEL process.
I got the wsdl loacation of the Web Service as "http://webservices.daelab.net/temperatureconversions/TemperatureConversions.wso?WSDL" and then in my workspace, I created a Web Service out of that WSDL.
My idea was to create a web service out of that WSDL and then to deploy that web service on SOA server so that i can invoke that deployed service in my BPEL process, but when i am creating a web service out of that WSDL , and trying to test the webservice in my local oc4j, i am gettting a fault exception.
Am i doing anything wrong ? Is there any other alternative to call a external web service in BPEL?
Thanks
NutanHi,
you are on the wrong track....
Open your BPEL. Put the http://webservices.daelab.net/temperatureconversions/TemperatureConversions.wso?WSDL into a PartnerLink and wire an invoke against this PartnerLink....
Put the parameters via assign into the variables.
Done...
Why do you want to create an interal webservice and invoke this one via BPEL? Do you want to invoke the external webservice from the internal one? -
Advice wanted: do i need threads or not?Stuck!
Hi, everyone! I got stuck with little program I'm writing and need your advice desperately.
I am doing temperature conversion program. In short, it's an applet with two JTextFields and four panels. JTextFields belong to the applet. Two panels are derivatives from my class called BasicThermometer extends JPanel. I made this class as flexible as I could, and it can draw pretty thermometer with needed ticks and ticks' labels as needed.
So, I've put two BasicTherm-s into my applet representing Celsius and Fahrenheit therm-rs respectively.
Other two panels are derivatives from my GradientPanel extends JPanel. They have gradient painted background with red and blue colors.
OK, here my final goal. When user input temp. to be converted in either text field converted temp. appears in other text field and tungsten of each therm-r reacts accordingly (I did that).
I can not accomplish my other task. Tungsten of each therm. responds on mouse event, so the user can input temp. by dragging or clicking it on either therm-r.( It's reacting allright). I want the temperature appear in each textfield and other therm-r tungsten move accordingly. I am unable to determine wether I need threads in it and if I do, how to design them. Should it be one thread or two? I am very new to multithreading and everything there is still blur to me. Also I'd like my gradient panels to react by fading gradient or thicken it on red (upper) panel or blue(lower panel).
I already set it flexible, so it's not a problem if I only could coordinate all my events properly.
Any advice will be helpful for me. I mean, maybe I have to change something in my classes-subclasses. To create new constructors maybe? How to deliver events from one JPanel so that the applet knew and pass it to other JPanel (i.e. to other BasicThermometer) so to repaint it as I want.In my thinking there could be thread or two that constatly tested one or other therm-r (while GUI thread is idling) and pass results to applet's method which resets other therm-r. Yesterday I failed to make them work. They worked two rounds right after start() even though my permit was set to false in each of the thermometers, and then stopped and did not wake if I clicked on either therm (I tested them by passing messages to be displayed in DOS).
Well, I am very confused. Sorry for lengthy message.
Svetlanatry my code
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
<applet code="CtoFConversion1.class" width=170 height = 170>
</applet>
public class CtoFConversion1 extends Applet implements ActionListener, ItemListener {
float c=0.0f;
float f=0.0f;
String msg="";
Checkbox checkbox1, checkbox2;
CheckboxGroup cbg;
TextField tf1,tf2;
Button convert, reset;
public void init() {
cbg = new CheckboxGroup();
checkbox1 = new Checkbox("Convert C to F",cbg, true);
checkbox2 = new Checkbox("Convert F to C",cbg, false);
convert = new Button("Convert");
reset = new Button("Reset");
Label centigrade = new Label("Centigrade :", Label.RIGHT);
Label fahrenheit = new Label("Fahrenheit :", Label.RIGHT);
tf1 = new TextField(10);
tf2 = new TextField(10);
add(checkbox1);
add(checkbox2);
add(centigrade);
add(tf1);
add(fahrenheit);
add(tf2);
add(convert);
add(reset);
checkbox1.addItemListener(this);
checkbox2.addItemListener(this);
tf1.addActionListener(this);
tf2.addActionListener(this);
convert.addActionListener(this);
reset.addActionListener(this);
tf2.setEditable(false);
public void itemStateChanged(ItemEvent ie) {
if((cbg.getSelectedCheckbox().getLabel()).equals("Convert C to F")) {
tf2.setEditable(false);
tf1.setEditable(true);
repaint();
if((cbg.getSelectedCheckbox().getLabel()).equals("Convert F to C")) {
tf1.setEditable(false);
tf2.setEditable(true);
repaint();
public void actionPerformed(ActionEvent ae) {
String command = ae.getActionCommand();
if(command.equals("Convert")) {
if((cbg.getSelectedCheckbox().getLabel()).equals("Convert C to F")) {
tf2.setEditable(false);
tf1.setEditable(true);
msg = tf1.getText();
try {
c = new Float(msg).floatValue();
msg="";
centi(c);
msg = msg+f;
tf2.setText(msg);
repaint();
}catch(NumberFormatException e){
tf2.setText("Syntax Error");
else if((cbg.getSelectedCheckbox().getLabel()).equals("Convert F to C")) {
tf1.setEditable(false);
tf2.setEditable(true);
msg = tf2.getText();
try {
c = new Float(msg).floatValue();
msg="";
fahren(c);
msg = msg+f;
tf1.setText(msg);
repaint();
}catch(NumberFormatException e){
tf1.setText("Syntax Error");
else if (command.equals("Reset")) {
tf2.setEditable(false);
tf1.setText("");
tf1.setEditable(true);
tf2.setText("");
checkbox1.setState(true);
repaint();
public float centi(float c){
f = (float)(1.8*c)+32.0f;
return f;
public float fahren(float c){
f = (float)(0.5556*(c-32.0));
return f;
} -
Printing "for" loop interations
Currently I'm stuck. I can't get more than the first interation of the two loops to print out on the same line. I can get the code to print all the interations if I run the loops seperately. But I'm trying to get the output of the two loops to print out side by side.
public class Project
public static void main(String[ ] args)
final double CELSIUS_TABLE_BEGIN = 40.0; // The table's first Celsius temperature
final double CELSIUS_TABLE_END = 31.0; // The table's final Celsius temperature
final double CELSIUS_TABLE_STEP = 1.0; // Increment between temperatures in table
final double FAHRENHEIT_TABLE_BEGIN = 120.0; // The table's first fahrenheit temperature
final double FAHRENHEIT_TABLE_END = 30.0; // The table's final fahrenheit temperature
final double FAHRENHEIT_TABLE_STEP = 10.0; // Increment between temperatures in table
double celsius; // A Celsius temperature
double fahrenheit; // The equivalent Fahrenheit temperature
double celsius1; // The equivalent Celsius temperature
double fahrenheit1; // A fahrenheit temperature
System.out.println(" TEMPERATURE CONVERSION ");
System.out.println("---------------------------------------------");
System.out.println("Celsius Fahrenheit Fahrenheit Celsius");
for (celsius = CELSIUS_TABLE_BEGIN; celsius <= CELSIUS_TABLE_END; celsius -= CELSIUS_TABLE_STEP)
for (fahrenheit1 = FAHRENHEIT_TABLE_BEGIN; fahrenheit1 <= FAHRENHEIT_TABLE_END; fahrenheit1 -= FAHRENHEIT_TABLE_STEP)
fahrenheit = celsiusToFahrenheit(celsius);
celsius1 = fahrenheitToCelsius(fahrenheit1);
System.out.printf( "%6.2fC %9.2fF %12.2fF %10.2fC \n", celsius, fahrenheit, fahrenheit1, celsius1);
System.out.println("---------------------------------------------");
public static double celsiusToFahrenheit(double c)
return (9.0/5.0)*c + 32;
} //end method
public static double fahrenheitToCelsius(double f1)
return (5.0/9.0)*(f1 - 32);
} //end method
} //end class <Project>Heres an example of how to loop in parallel:
public static void main (String[] args) {
int j = 5;
int k = 10;
for(int m = j, n = k; m > 0 || n > 0; m--, n--) {
//Print m and n
if(m > 0 && n > 0) {
System.out.printf("m := %5d%10sn := %5d", m,"", n);
//Print m
else if (m > 0) {
System.out.printf("m := %5d", m);
//Print n
else {
System.out.printf("%20sn := %5d", "", n);
System.out.println();
}Output:
m := 5 n := 10
m := 4 n := 9
m := 3 n := 8
m := 2 n := 7
m := 1 n := 6
n := 5
n := 4
n := 3
n := 2
n := 1Mel -
HELP!!! NumberFormatException!!!
Can you find anything wrong this code that causes a NumberFormatException? I'm a beginner, so I haven't got to exception handling yet. I'm working from Deitel and Deitel's book "Java 2: How to Program". I don't care what number I put in (with or without a decimal point), the exception is always there. I don't see anything wrong with the code. Do you? Please feel free to copy this code and use it on your own computer, and let me know what works for you. Your help will be greatly appreciated. Here I've posted the code and below it is the runtime error message.
// Exercise 12.13
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Temperature extends JFrame
private JLabel enterTemp, convertTemp;
private JTextField tempField, resultsField;
private JComboBox scales;
private JRadioButton scaleButtons[];
private ButtonGroup rbGroup;
private JPanel top, middle, bottom;
private Container c;
private String scaleNames[] = {"Fahrenheit", "Centigrade", "Kelvin"};
private RadioButtonHandler handler;
public Temperature()
super("Temperature Conversion App");
c = getContentPane();
c.setLayout(new GridLayout(3,1));
setupTop();
setupMiddle();
setupBottom();
setSize(500,300);
show();
public void setupTop()
top = new JPanel();
top.setLayout(new FlowLayout());
enterTemp = new JLabel("Please enter a temperature:");
top.add(enterTemp);
tempField = new JTextField(5);
top.add(tempField);
scales = new JComboBox(scaleNames);
scales.setMaximumRowCount(1);
top.add(scales);
c.add(top);
public void setupMiddle()
middle = new JPanel();
middle.setLayout(new FlowLayout());
convertTemp = new JLabel("I wanna convert this to:");
middle.add(convertTemp);
handler = new RadioButtonHandler();
scaleButtons = new JRadioButton[3];
rbGroup = new ButtonGroup();
for (int i=0; i < scaleButtons.length; i++)
scaleButtons[i] = new JRadioButton(scaleNames, false);
scaleButtons[i].addItemListener(handler);
rbGroup.add(scaleButtons[i]);
middle.add(scaleButtons[i]);
c.add(middle);
public void setupBottom()
bottom = new JPanel();
bottom.setLayout(new FlowLayout());
resultsField = new JTextField(50);
resultsField.setEditable(false);
bottom.add(resultsField);
c.add(bottom);
private class RadioButtonHandler implements ItemListener
public void itemStateChanged(ItemEvent e)
if (e.getSource()==scaleButtons[0])
if (scales.getSelectedIndex()==0)
resultsField.setText("You already have the Fahrenheit temp!");
else if (scales.getSelectedIndex()==1)
convertF2C(enterTemp.getText());
else if (scales.getSelectedIndex()==2)
convertF2K(enterTemp.getText());
} // end if
if (e.getSource()==scaleButtons[1])
if (scales.getSelectedIndex()==0)
convertC2F(enterTemp.getText());
else if (scales.getSelectedIndex()==1)
resultsField.setText("You already have the Centigrade temp!");
else if (scales.getSelectedIndex()==2)
convertC2K(enterTemp.getText());
} // end if
if (e.getSource()==scaleButtons[2])
if (scales.getSelectedIndex()==0)
convertK2F(enterTemp.getText());
else if (scales.getSelectedIndex()==1)
convertK2C(enterTemp.getText());
else if (scales.getSelectedIndex()==2)
resultsField.setText("You already have the Kelvin temp!");
} // end itemStateChanged
} // end RadioButtonHandler
public void convertF2C(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Fahrenheit is "+((5/9)*(temp-32)) + " degrees
Centigrade.");
public void convertF2K(String input)
{ double temp = 0.0;
temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Fahrenheit is "+((5/9)*(temp-32)+273) + " degrees
Kelvin.");
public void convertC2F(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Centigrade is " +((9/5)*temp+32) + " degrees
Fahrenheit.");
public void convertC2K(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Centigrade is " +(temp+273) + " degrees Kelvin.");
public void convertK2F(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Kelvin is " +((9/5)*(temp-273)+32) + " degrees
Fahrenheit.");
public void convertK2C(String input)
double temp = Double.parseDouble(input);
resultsField.setText(temp + " degrees Kelvin is " + (temp-273) + " degrees Centigrade.");
public static void main(String args[])
Temperature app = new Temperature();
app.addWindowListener(new WindowAdapter()
public void windowClosing(WindowEvent e)
System.exit(0);
} // end main
} // end class
C:\jdk1.2.1\bin>java Temperature
Exception occurred during event dispatching:
java.lang.NumberFormatException: Please enter a temperature:
at java.lang.FloatingDecimal.readJavaFormatString(Compiled Code)
at java.lang.Double.parseDouble(Double.java:188)
at Temperature.convertC2F(Temperature.java:129)
at Temperature$RadioButtonHandler.itemStateChanged(Temperature.java:95)
at javax.swing.AbstractButton.fireItemStateChanged(Compiled Code)
at javax.swing.AbstractButton$ForwardItemEvents.itemStateChanged(Abstrac
tButton.java:1112)
at javax.swing.DefaultButtonModel.fireItemStateChanged(Compiled Code)
at javax.swing.JToggleButton$ToggleButtonModel.setSelected(JToggleButton
.java:222)
at javax.swing.JToggleButton$ToggleButtonModel.setPressed(JToggleButton.
java:239)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonL
istener.java:217)
at java.awt.Component.processMouseEvent(Component.java:3126)
at java.awt.Component.processEvent(Compiled Code)
at java.awt.Container.processEvent(Compiled Code)
at java.awt.Component.dispatchEventImpl(Compiled Code)
at java.awt.Container.dispatchEventImpl(Compiled Code)
at java.awt.Component.dispatchEvent(Compiled Code)
at java.awt.LightweightDispatcher.retargetMouseEvent(Compiled Code)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:1732)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:1645)
at java.awt.Container.dispatchEventImpl(Compiled Code)
at java.awt.Window.dispatchEventImpl(Window.java:714)
at java.awt.Component.dispatchEvent(Compiled Code)
at java.awt.EventQueue.dispatchEvent(Compiled Code)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:68)Of course you can also just stick your code in a try... catch block and handle the exceptions as they arise. This would probably be sub-optimal if you were getting a lot of them though.
Of course you could combine both and create a helper method to parse your double values.
public double getDoubleValueFromString(String input) {
double myDouble = 0;
try {
if(!isEmptyOrNull(input)) {
myDouble = Double.parseDouble(input);
catch (NumberFormatException ex) {
// Handle this exception how ever you want.
finally {
// This is to annoy a certain somebody in the forums
return myDouble; -
If (message == "FC") evaluates to false
The answer to this is probably simple, but If-Then-Else is fundamental enough that I have got to be able to work with it.
My Class is below:
import java.io.*;
// Print a Fahrenheit to Celsius table
///* °C x 9/5 + 32 = °F. */
class Celsius2Fahr
public static void main (String args[])
try
String message, message2;
boolean blnTF;
System.out.println("Enter FC for a list of Fahr to Celsius, T for one temperature conversion");
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader stdin = new BufferedReader(isr);
message = stdin.readLine();
int fahr, celsius;
int lower, upper, step;
lower = -50; // lower limit of temperature table
upper = 300; // upper limit of temperature table
step = 20; // step size
System.out.println("Celsius Fahrenheit-1");
if (message == "FC")
celsius = lower;
System.out.println("Celsius Fahrenheit-2");
while (celsius <= upper)
{ // while loop begins here
fahr = (celsius * 9 / 5) + 32;
System.out.print(celsius);
System.out.print(" ");
System.out.println(fahr);
celsius = celsius + step;
} // while loop ends here
} // If ends here
else
System.out.println("Enter the Fahrenheit Temp to convert: ");
BufferedReader stdin2 = new BufferedReader
(new InputStreamReader(System.in));
message2 = stdin2.readLine();
fahr = (Integer.parseInt(message2) * 9 / 5) + 32;
} //End of Else
} // try
catch (IOException e)
} //public static void main (String args[])
} // class Celsius2Fahr2
message is a string so (message == "FC) should evaluate to true when I enter "FC", but it evaluates to False and the If Then code never executes. If I change this to (message = "FC), single "=" sign, I get the error: "Type mismatch: cannot convert from String to boolean"
So regardless of what I enter for the first questions, I get this sort of output, and System.out.println("Celsius Fahrenheit-2"); is never executed.
Enter FC for a list of Fahr to Celsius, T for one temperature conversion
FC
Celsius Fahrenheit-1
Enter the Fahrenheit Temp to convert:
56
Any help would be appreciated.jverd wrote:
sharkura wrote:
jverd wrote:
When posting code, use code tags so it will be readable.
Having read only your subject line, and not your voluminous and unformatted code, my crystal ball tells me you need to use equals(), not ==, for comparing objects' states (including Strings' contents).Unless, of course, you wish to test if the references point to the same object in memory.Which is why I said "...for comparing objects' states". Though I guess I didn't present my comment clearly enough. It came out halfway between how to address his problem in particular (which, theoretically could have been about comparing references) and the general advice to "do this when you want that."
P.S. Hi Sharky! :-)Hi. Long time no see. I've been on a sabbatical for so long, they took away all my posts!
¦{Þ -
Did the developers of the DAQmx drivers improve the temperature scan capability of the SXCI 1120 module over the methods used in the traditional drivers?
When using the SCXI 1120 module for temperature measurement and in the continuous scan mode with traditional drivers the cold junction reference was only checked on the initial start of the scan. In order to maintain accuracy it was necessary to restart the scan.
For the most part I have switched to the 1125 module for thermocouple measurement but I need to use some 1120 modules on a test stand now and I will be using the DAQmx drivers on these. I was in hopes that with the DAQmx drivers this behavior was corrected.
I can conduct testing to determine this but would like to know ahead of time if this is still an issue.
ThanksThank you Ben for the answer.
I checked the article you referenced appears to me that I will be adding the physical address in the channel strings then do the voltage to temperature conversion and then correct the appropriate channels associated with the cjc in question. I will also need to adjust some on board jumpers for the SCXI 1120. If I am wrong please correct me.
If scanning the physical channel is possible as suggested in this article, would it not be possible to create the channel as a virtual global channel and reference it as the cold junction in Max? Then the temperature adjustment could be done at this level of acquisition rather than having to sort this out in the LabVIEW program. This takes me back to the days with LabVIEW 4.0 before we had the virtual channels and when we had to handle the temperature conversions and other scaling ourselves. Again if I am incorrect please let me know, for I would like to use the method recommended in the article if I don't have to perform all the calculations in the application.
Just wondering if anybody reading this has actually used this method. If so, how did it work for you?
I may end up building a start up routine testing for 1120 modules being used for thermocouple measurement then if found run a stop and restart scan every 5 minutes to prevent large errors from being introduced.
Maybe you are looking for
-
CE: Autorec for Multi Bank Stmt Lines to one Receipt in Open Interface
We have a requirement to auto reconcile multiple bank statement lines to a single receipt in the Open interface table. We are on 11.5.10.2 and unable to autoreconcile. Could some one tell me how can we automatically reconcile two bank statement lines
-
I'm looking for a research position in Salt Lake City
Gary Vardon 4216 S. Bannock Drive West Valley City, Utah, 84120 801-969-7432 Educational Experience B.S., Chemistry, 1975 Metro State College Chemistry major Electrical Engineering minor Denver, Colorado M.S., Natural Science, 1976 Louisiana State Un
-
Tp import flag not properly set in "STMS", tp-processe not ended
since last Stopping of our Q-System the display in of the import queue doesnt work fine. when we transport requests from the development-system to the q-system the truck-icon doesn't disappear. the processes in AIX are not finished, after time the "
-
Infoset Enhancement removed by moderator
Hi, i am using BW 3.5 with patch 16. i have did the enhancement for my sales ODS and above that i have one Infoset... can someone tell me how to add this field to the infoset..... i have tried the following... i have deactivated the infoset to see th
-
ITtunes doesn't offer new iOS updates for my iPad 2.
Although I manually checked with the Update button, it states that my iOS 4.3.5 is on the actual state. Any hints?