Search code examples
javaswingjtextfield

JTextField input to Double


I am working on an application that gets a shutter speed that a user enters into a text field. The user can type in a shutter speed in the form of a fraction "1/250" or a whole number. From that input I want to convert that to a variable of type double.

But when I try inputting "1/250" I get many errors, the first being:

Exception in thread "AWT-EventQueue-0" java.lang.NumberFormatException: 
    For input string: "1/250"

I know it has to do with the '/' in the input but how would I go about converting the fraction to a double?

        JTextField userShutter = new JTextField("", 10);
        userShutter.setBounds(60, 180, 50, 25);

        userShutter.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                double shutter = Double.parseDouble(userShutter.getText());
                baseShutterSpeed = shutter;
            }
        });

        // Calculate shutter speed
        calculator(stopValue, baseShutterSpeed);

Solution

  • You simply need to use the String that you are getting back from the textfield and split it into two parts based on the / character. Then you can use those two numbers and divide them like you would using basic math to get the double.

    String str = userShutter.getText();
    String[] arr = str.split("/");
    
    double answer = Double.parseDouble(arr[0]) / Double.parseDouble(arr[1]);
    System.out.println(answer);