
-----------------------------------
Fasih
Thu Mar 24, 2011 7:27 pm

Handling fractions
-----------------------------------
Ok so I'm making a fraction program for class, but I can't seem to make the program accept a whole number because im finding  fract.indexOf ('/'); for the actual fractions so i can work around the "/" and get the numerator and denominator. But because of that, if i enter a whole number, I get a [CODE]java.lang.StringIndexOutOfBoundsException: String index out of range: -1[/CODE]
error. 

Note I am reading the fractions as a String ;)

Heres the read function in my class:

[CODE]public void read (String fract)
    {        
        pos = fract.indexOf ('/');
        numerS = fract.substring (0, pos);
        denomS = fract.substring (pos + 1);

        
        boolean check = false;
        while (!check)
        {
            try
            {

                numer = Integer.parseInt (numerS);
                denom = Integer.parseInt (denomS);
                check = true;
            }
            catch (NumberFormatException x)
            {
                //System.out.print ("Invalid Input, try again");
                read (fract);
            }
        }

    }[/CODE]
Can someone tell me what to add? 

Also, how do I force the user to enter another number if it catches the exception. I am doing a GUI and this Fraction class is separate from my GUI class.

-----------------------------------
Insectoid
Thu Mar 24, 2011 7:32 pm

RE:Handling fractions
-----------------------------------
Just check if fract.indexof ('/') is -1. If it is, there's no fraction. If it's greater than 0, there's a fraction.

-----------------------------------
Fasih
Thu Mar 24, 2011 7:37 pm

RE:Handling fractions
-----------------------------------
But I want to allow whole numbers.

Like if a user inputs a 8 into the textfield then that 8 would be the numerator and the denominator would be 1

-----------------------------------
Insectoid
Thu Mar 24, 2011 7:43 pm

RE:Handling fractions
-----------------------------------
And if there's no '/' (indexof returns -1) then you know it's a whole number, and you can account for it.

-----------------------------------
Fasih
Thu Mar 24, 2011 7:50 pm

RE:Handling fractions
-----------------------------------
Ooh ok it works now!

Also for the other question I had in my post, if it catches the exception, how can I make the user re-enter the value. Its in a GUI which is in another class, and from the GUI I'm calling this class.
