I have a TextField where I can type values; And I need to convert the value typed to Int and display it with S.O.Println.
EDIT:
I've tried now :
try {
int i = Integer.parseInt(myText.getText());
System.out.println("This is an integer " + i);
}
catch (NumberFormatException x) {
System.out.println("Error : "+ x.getMessage());
}
But it's giving me :
This is an integer 122 // When I type 122
Error : For input string: "122,5" // When I type 122,5
Error : For input string: "122.5" // When I type 122.5
Any ideas.
EDIT:
This is it :
开发者_开发问答double d = Double.parseDouble(myText.getText());
int i = (int)d;
It appears you are using a comma as a separator, rather than a point. And anyway, you wouldn't be able to parse it as int
. You'd need Double.parseDouble(..)
Use can use NumberFormat
corresponding to the current locale in order to parse the input.
If you are using SWT (tagged eclipse) - I think you can limit the possible characters by adding a VerifyListener
to the text field. In your listener, call doit()
on the passed event if the input is allowed.
If using AWT (TextField
being awt's text component) - then see something like this
You try to parse string "11,5" as integer. It is definitely not integer. Therefore the exception is thrown.
You can try to use Double.parseDouble() and the result depends on your Locale. If you are in English locale it expects dot (.) and not coma, so the number anyway should look like 11.5
The comma is giving you a parse error. If you require the comma, you can use it as a delimiter and parse the two sides separately.
Here is an example of separating two comma separated values in a string.
String str = "1,2,3,4";
StringTokenizer st = new StringTokenizer(str, ",");
while (st.hasMoreTokens()) {
System.out.println(st.nextToken());
}
The output would be:
1
2
3
4
11,5
is not a number that Java can parse without other interaction. You can replace the comma with a decimal point, along with removing any spaces (depending on your locale):
Double.parseDouble(myText.getText().replaceAll(",", ".").replaceAll(" ", ""));
Notes:
You cannot use the comma as a thousands separator.
That's because the myText.getText()
is 11,5
(not numeric) and not 11.5
(double).
Try doing,
Double.parseDouble(myText.getText().replaceAll(",", "."));
This replaces ,
to .
.
Alternatively, uses NumberFormat
to do your number conversion.
Also, I've noticed you're using Integer.parseInt()
when parsing double
numbers. That's why you're having exceptions thrown.
You should use NumberFormat.getInstance(locale).parse(myText.getText())
to get your required result. Don't forget that parse()
returns a Number
object, so to get a double, do this:
double d = NumberFormat.getInstance(locale).parse(myText.getText()).doubleValue();
精彩评论