2013-02-20 45 views
1

轉換用戶的米英尺和英寸與添加字符串和int值在一個JTextField中

//  following format (16ft. 4in.). Disable the button so that 
//  the user is forced to clear the form. 

輸入的問題是,我不知道如何把字符串和int值在一個文本字段如果else語句

private void ConversionActionPerformed(ActionEvent e) 
    { 
     String s =(FourthTextField.getText()); 
     int val = Integer.parseInt(FifthTextField.getText()); 

     double INCHES = 0.0254001; 
     double FEET = 0.3048; 
     double meters; 

     if(s.equals("in")) 
     { 
      FourthTextField.setText(" " + val*INCHES + "inch"); 
     } 
     else if(s.equals("ft")) 
     { 
      FourthTextField.setText(" " +val*FEET + "feet"); 
     } 
    } 

比我如何能在他們設定爲能夠加入一個JTextField字符串和int值?

+2

'FourthTextField'請給予控件有意義的名稱。還請學習類的常用[Java命名約定](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#73307)(具體用於名稱的情況)方法和屬性名稱並一致使用它。 – 2013-02-20 04:36:04

回答

2

你可以這樣做......

FourthTextField.setText(" " + (val*INCHES) + "inch"); 

FourthTextField.setText(" " + Double.toString(val*INCHES) + "inch"); 

FourthTextField.setText(" " + NumberFormat.getNumberInstance().format(val*INCHES) + "inch"); 

更新

如果您所關心的的是提取文本的數字部分,你可以做這樣的事情...

String value = "1.9m"; 
Pattern pattern = Pattern.compile("\\d+([.]\\d+)?"); 

Matcher matcher = pattern.matcher(value); 
String match = null; 

while (matcher.find()) { 

    int startIndex = matcher.start(); 
    int endIndex = matcher.end(); 

    match = matcher.group(); 
    break; 

} 

System.out.println(match); 

這將輸出1.9,具有m剝離後的每一個。這將允許您提取String的數字元素並將其轉換爲數字進行轉換。

這將處理整個和十進制數字。

+0

不,像我要問用戶時,他們想要什麼價值,例如用戶填充16米,而不是我的if else聲明如何知道價值 – CRazyProgrammer 2013-02-20 04:38:27

+0

授予用戶從選項中進行選擇,無論輸入的值是米或英寸等。然後得到值的選項,並在裏面匹配,如果你正在做 – exexzian 2013-02-20 04:46:34

+0

而關於設置整數和字符串,@madprogrammer已經回答了 – exexzian 2013-02-20 04:48:36

相關問題