Java 边界外例外;使用分数

Java 边界外例外;使用分数,java,trim,indexoutofboundsexception,fractions,Java,Trim,Indexoutofboundsexception,Fractions,我正在编写一个名为FractionScaler的程序,它使用扫描器从用户那里获取分数,然后对其进行操作。我已经写了一个分数类来处理所有的计算。用户应该输入这样的分数:“2/3”或“43/65”等。。。这部分工作正常,问题是当整数之间有空格时:“3/4”或“2/5”等。。。出现“OutOfBoundsException:字符串索引超出范围:-1”。让我进一步解释 //This is the user inputted fraction. i.e. "2/3" or " 3 / 4"

我正在编写一个名为FractionScaler的程序,它使用扫描器从用户那里获取分数,然后对其进行操作。我已经写了一个分数类来处理所有的计算。用户应该输入这样的分数:“2/3”或“43/65”等。。。这部分工作正常,问题是当整数之间有空格时:“3/4”或“2/5”等。。。出现“OutOfBoundsException:字符串索引超出范围:-1”。让我进一步解释

    //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
我认为应该留下两个看起来像整数的字符串,现在我需要把这些字符串转换成实际的整数

    //converts string "integer" into real int
    int num = Integer.parseInt(sNum); 
    int denom = Integer.parseInt(sDenom);
现在我有了分子和分母的两个整数,我可以将它们插入我编写的分数类的构造函数中

    Fraction fraction1 = new Fraction(num, denom);
我怀疑这是最好的办法,但这是我能想到的唯一办法。当用户输入的分数没有空格时,例如“2/3”或“5/6”,程序工作正常。 当用户输入有任何类型的空格时,例如“3/4”或“3/4”,显示以下错误:

线程“main”java.lang.StringIndexOutOfBoundsException中出现异常:字符串索引超出范围:-1

终端指向代码的第17行,即上面的这一行:

    String sNum = frac.substring(0,slashLocate);
我不知道为什么会出现越界错误。其他人能猜出来吗

如果有什么不清楚或者我没有提供足够的信息,就说出来


非常感谢。

试试
String frac=scan.nextLine()
我认为
next()
在空格后不会得到任何东西。

来自:

扫描仪使用分隔符模式将其输入拆分为标记, 默认情况下与空白匹配

这意味着这将不起作用,因为当输入
2/3
时,
frac
将只包含文本
“2”


请张贴堆栈跟踪,并标记获得异常的行。每次打印
frac
,或者在出现错误时从
catch
块打印,都可以轻松测试。谢谢jhobbie!这就是问题所在!
String frac = scan.next();

//This finds the slash separating the numerator from the denominator 
int slashLocate = frac.indexOf("/");