Search code examples
javatrimindexoutofboundsexceptionfractions

OutOfBounds Exception ; working with Fractions


I'm writing a program called FractionScaler that takes in a fraction from the user using Scanner, and then manipulates it. I've written a fraction class that handles all the calculations. The user is supposed to enter a fraction like this: "2/3" or "43/65" etc... This part works fine, the problem is when there is space between the integers: " 3 / 4 " or "2/ 5" etc... An "OutOfBoundsException: String index out of range: -1" occurs. Let me explain further.

    //This is the user inputted fraction.  i.e. "2/3" or "  3  / 4"

    String frac = scan.next();

    //This finds the slash separating the numerator from the denominator 

    int slashLocate = frac.indexOf("/");

    //These are new strings that separate the user inputted string into two parts on 
    //either side of the "/" sign

    String sNum = frac.substring(0,slashLocate); //This is from the beginning of string to the slash (exclusive)
    String sDenom = frac.substring(slashLocate+1,frac.length()); //from 1 after slash to end of string

    //This trims the white space off of either side of the integers
    sNum = sNum.trim();  //Numerator
    sDenom = sDenom.trim();  //Denominator

What I thought should be left is just two strings that look like integers, now I need to turn those strings into actual integers.

    //converts string "integer" into real int
    int num = Integer.parseInt(sNum); 
    int denom = Integer.parseInt(sDenom);

Now that I have two integers for the numerator and the denominator, I can plug them into a constructor for the fraction class I wrote.

    Fraction fraction1 = new Fraction(num, denom);

I doubt this is the best way to go about this, but it is the only way I could think of. When the user inputted fraction has no spaces, EX. "2/3" or "5/6" , the program works fine. When the user input has spaces of any kind, EX. "3 / 4" or " 3 /4" , the following error is shown:

Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1.

The terminal points to line 17 of my code which is this line above:

    String sNum = frac.substring(0,slashLocate);

I don't know why I'm getting an out of bounds error. Can anyone else figure it out?

If something is unclear or I didn't give enough info, just say so.

Thanks very much.


Solution

  • Try String frac = scan.nextLine(); I think next() won't get anything after a space.