1

将用户输入的米转换为英尺和英寸

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

问题是我不知道如何将字符串和 int 值放在一个文本字段中,而不是如何在 if 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");
         }
   }

是否可以同时添加字符串和 int 值JTextField

4

1 回答 1

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并转换为数字进行转换。

这将处理整数和小数。

于 2013-02-20T04:35:37.013 回答