接收StringIndexOutOfBoundsException但无法找到源

时间:2015-03-06 19:35:08

标签: java substring

我的任务: 使用scanner method从数据行中提取字符串,浮点数和int。

数据格式为:

Random String, 240.5 51603
Another String, 41.6 59087

我的源代码段:

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.Scanner;
    public class readTest { 

        public static void main(String args[]) throws FileNotFoundException
          {

            System.out.println ("Enter file name");

            Scanner scanInput = new Scanner(System.in); //Scanner for reading keyboard input for file name
            String fileName = scanInput.nextLine(); //Defines file name as a string from keyboard
            File inputTxt = new File(fileName); //Declares the file based on the entered string
            Scanner in = new Scanner(inputTxt);

            do {

            int a; //variable to count how many characters in name
            String baseStringA = in.nextLine(); //read whole line as string
            a = baseStringA.indexOf(","); //defines a as the posistion of the comma
            String reduceStringA = baseStringA.substring(0, a); //reduces string to everything before comma

            Scanner scanA = new Scanner(baseStringA).useDelimiter("[^.0-9]+"); //removes letters and comma from string
            Float numberA = scanA.nextFloat();
            int integerA = scanA.nextInt();

            System.out.print (reduceStringA + numberA + integerA);

            } while (in.hasNextLine());
}
}

所以我在研究了几个不同的主题(我对任何类型的编码都很陌生)之后终于设法吐出这些代码而且我非常兴奋以至于我设法得到了我想要的输出。但是在尝试实现循环以使进程对所有可用行重复之后,在程序打印第一行的输出后,我经常遇到错误java.lang.StringIndexOutOfBoundsException。

完整错误:

String index out of range: -1
    at java.lang.String.substring(Unknown Source)
    at readTest.main(readTest.java:43)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)

我试着研究一下,我确信它来自我的行

String reduceStringA = baseStringA.substring(0, a);

当我试图读取错误给出的实际信息时,这似乎更加明显,但是当我试图追踪程序出现问题的地方时,我出现了空白。

有人能够发现我的菜鸟错误吗?或者我只是完全错误地处理这个过程?

输入txt:

Stringy String, 77.2  36229 
More Much String, 89.4 24812
Jolly Good String, 182.3 104570

是我收到错误的一个例子

输入

Random String, 240.5 51603
Another String, 41.6 59087
String String, 182.6 104570

按预期工作

这对我来说真的很奇怪。

1 个答案:

答案 0 :(得分:2)

        int a; //variable to count how many characters in farm name
        String baseStringA = in.nextLine(); //read whole line as string
        a = baseStringA.indexOf(","); //defines a as the posistion of the comma
        String reduceStringA = baseStringA.substring(0, a);

如果baseStringA baseStringA.indexOf() will return -1中没有逗号。因此,您将尝试获取子字符串(0,-1),从而获得错误。

最后,错误来自此处baseStringA.substring(0, a);,因为其中一个开头索引0大于结束索引a(即-1) - 更多here