テキストフィールドから入力を取得して整数に変換するJFrameがあります。また、doubleの場合はdoubleに変換し、intでもdoubleでもない場合はメッセージを返したいと思います。これどうやってするの?
私の現在のコード:
int textToInt = Integer.parseInt(textField[0].getText());
テキストフィールドから入力を取得して整数に変換するJFrameがあります。また、doubleの場合はdoubleに変換し、intでもdoubleでもない場合はメッセージを返したいと思います。これどうやってするの?
私の現在のコード:
int textToInt = Integer.parseInt(textField[0].getText());
String text = textField[0].getText();
try {
int textToInt = Integer.parseInt(text);
...
} catch (NumberFormatException e) {
try {
double textToDouble = Double.parseDouble(text);
...
} catch (NumberFormatException e2) {
// message?
}
}
精度を維持するには、すぐにBigDecimalに解析します。もちろん、このparseDoubleはロケール固有ではありません。
try {
int textToInt = Integer.parseInt(textField[0].getText());
} catch(NumberFormatException e) {
try {
double textToDouble = Double.parseDouble(textField[0].getText());
} catch(NumberFormatException e2) {
System.out.println("This isn't an int or a double";
}
}
boolean isInt = false;
boolean isDouble = false;
int textToInt = -1;
double textToDouble = 0.0;
try {
textToInt = Integer.parseInt(textField[0].getText());
isInt = true;
} catch(NumberFormatException e){
// nothing to do here
}
if(!isInt){
try {
textToDouble = Double.parseDouble(textField[0].getText());
isDouble = true;
} catch(NumberFormatException e){
// nothing to do here
}
}
if(isInt){
// use the textToInt
}
if(isDouble){
// use the textToDouble
}
if(!isInt && !isDouble){
// you throw an error maybe ?
}
文字列に小数点が含まれているかどうかを確認してください。
if(textField[0].getText().contains("."))
// convert to double
else
// convert to integer
例外を投げる必要はありません。
上記を実行する前に、正規表現を使用して文字列が数値であるかどうかを確認できます。1つの方法は、パターンを使用すること[0-9]+(\.[0-9]){0,1}
です。私は正規表現が得意ではないので、これが間違っている場合は修正してください。
ネストされた一連のトライキャッチを試すことができます。
String input = textField[0].getText();
try {
int textToInt = Integer.parseInt(input);
// if execution reaches this line, it's an int
} catch (NumberFormatException ignore) {
try {
double textToDouble = Double.parseDouble(input);
// if execution reaches this line, it's a double
} catch (NumberFormatException e) {
// if execution reaches this line, it's neither int nor double
}
}