2013-03-27 88 views
0

我有一個JFrame,我從文本字段獲取輸入並將其轉換爲整數。 我也想將它轉換爲double,如果它是一個double,並且可能會返回一條消息,如果它不是int或double。我怎樣才能做到這一點?根據輸入將文本輸入轉換爲int或double

我當前的代碼:

int textToInt = Integer.parseInt(textField[0].getText()); 
+0

分析和捕獲異常? – VirtualTroll 2013-03-27 12:50:13

回答

3
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當然不是語言環境特定的。看到

1
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"; 
    } 
} 
1
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 ? 
} 
0

檢查如果字符串包含小數點。

if(textField[0].getText().contains(".")) 
    // convert to double 
else 
    // convert to integer 

沒有必要拋出異常。

在執行上述操作之前,您可以檢查字符串是否是使用正則表達式的數字。一種方式是模式[0-9]+(\.[0-9]){0,1}。我不是最好的正則表達式,所以請糾正我,如果這是錯誤的。

+0

所以「foo.bar」是一個有效的雙? – Bohemian 2013-03-27 12:58:44

+0

我意識到並正在編輯我的答案,因爲您發佈了您的評論:) – mage 2013-03-27 13:03:22

+0

更好,但1000位數字呢? Double有最大值和最小可表示值。 – Bohemian 2013-03-27 13:09:28

0

你可以嘗試一系列嵌套的try-漁獲物:

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 
    } 
}