Search code examples
javaswingjtextfield

Add both string and int value in one JTextField


Convert user input of meters to feet and inches with the

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

Problem is that I don't know how to put both string and int value in one text Field, than how can i set them to in if else statement

   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");
         }
   }

Is it possible to add both string and int value in one JTextField?


Solution

  • You could do ...

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

    or

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

    or

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

    Updated

    If all you care about is extract the numeric portion of the text, you could do something like this...

    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);
    

    This will output 1.9, having stripped of every after the m. This would allow you to extract the numeric element of the String and convert to a number for conversion.

    This will handle both whole and decimal numbers.