0

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);
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Kev
  • 33
  • 2
  • 6
  • 1
    `"1/250"` isn't a `double` ... why would you think it was? You need to take the text, split on the `/` delimiter and then you can start converting the text to numbers and performing the required maths to convert it an appropriate double value – MadProgrammer Nov 12 '18 at 22:47
  • @MadProgrammer *"You need to.."* ..use the `ScriptEngine` to evaluate the expression? OK maybe it's just my laziness that makes me suggest that. – Andrew Thompson Nov 12 '18 at 23:57
  • 1
    @AndrewThompson I just grew up in an era that don't have "fancy pancy" scripting engines ;) – MadProgrammer Nov 13 '18 at 00:06
  • `userShutter.setBounds(60, 180, 50, 25);` Java GUIs have to work on different OS', screen size, screen resolution etc. using different PLAFs in different locales. As such, they are not conducive to pixel perfect layout. Instead use layout managers, or [combinations of them](http://stackoverflow.com/a/5630271/418556) along with layout padding and borders for [white space](http://stackoverflow.com/a/17874718/418556). – Andrew Thompson Nov 13 '18 at 00:23

1 Answers1

1

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