newbie jtextfield question
so, i'm trying for a user to enter number in jtextfields and then when they press jbutton to add...the program takes the 2 numbers entered and adds them up....my program actually somewhat works but i'm converting from text to double and then back to text to be able to print the number in jlabel. I need your help in simplifying the code please. TKS.
public void actionPerformed(ActionEvent ae)
{
String text1 = one.getText();
double aDouble = Double.parseDouble(text1);
String text2 = two.getText();
double bDouble = Double.parseDouble(text2);
double answer = aDouble + bDouble;
String aString = Double.toString(answer);
testing.setText(aString);
}
});
Re: newbie jtextfield question
Quote:
need your help in simplifying the code
What needs to be simplified?
It looks simple to me. Any changes would make it more complicated.
You have one statement for each step that needs to be taken.
Re: newbie jtextfield question
Ok. cool. also, If the user enters something that's not a double/int I need to have it set to 0 in that case. I looked and can't find anything that will do that for me. How can i check if the user actually entered a double and if he/she didn't, use the value of 0?
Re: newbie jtextfield question
parseDouble() will throw an exception if the string argument cannot be parsed as a double. Catch the exception, and set the value equal to zero in that case.
Double (Java Platform SE 6)
Lesson: Exceptions (The Java™ Tutorials > Essential Classes)
Re: newbie jtextfield question
Ok. Tks. I found that online, thought there would be an easier way.....Let me try this and see what happens....TKS FOR THE HELP
Re: newbie jtextfield question
Instead of catching exceptions, can i use a scanner let's say to identify if the input is a double? Wouldn't that be a more effective way of doing it?
Re: newbie jtextfield question
Are you suggesting that You would take the String from the text field, create another object with the String and then ask that object if the data it has is a valid double?
What do you mean by "more effective"?
Re: newbie jtextfield question
yeah, you're right.......I read the exceptions stuff and input in my program and works like a charm....thanks man...
Code:
public void actionPerformed(ActionEvent ae)
{
String text1 = one.getText();
String text2 = two.getText();
try {
aDouble = Double.parseDouble(text1);
} catch (NumberFormatException e)
{
aDouble = 0;
}
try {
bDouble = Double.parseDouble(text2);
} catch (NumberFormatException e)
{
bDouble = 0;
}