Programming C, C++, Java, PHP, Ruby, Turing, VB
Computer Science Canada 
Programming C, C++, Java, PHP, Ruby, Turing, VB  

Username:   Password: 
 RegisterRegister   
 Handling fractions
Index -> Programming, Java -> Java Help
View previous topic Printable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic
Author Message
Fasih




PostPosted: Thu Mar 24, 2011 7:27 pm   Post subject: 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

error.

Note I am reading the fractions as a String Wink

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

    }

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.
Sponsor
Sponsor
Sponsor
sponsor
Insectoid




PostPosted: Thu Mar 24, 2011 7:32 pm   Post subject: 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




PostPosted: Thu Mar 24, 2011 7:37 pm   Post subject: 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




PostPosted: Thu Mar 24, 2011 7:43 pm   Post subject: 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




PostPosted: Thu Mar 24, 2011 7:50 pm   Post subject: 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.
Display posts from previous:   
   Index -> Programming, Java -> Java Help
View previous topic Tell A FriendPrintable versionDownload TopicSubscribe to this topicPrivate MessagesRefresh page View next topic

Page 1 of 1  [ 5 Posts ]
Jump to:   


Style:  
Search: