IndexOf(), String index out of bounds: -1

隐身守侯 提交于 2019-12-14 03:58:55

问题


I have no idea what is happening. I have a list of products along with a number separated with a tab. When I use indexOf() to find the tab, I get a String index out of bounds error, and it says the index is -1. Here's the code:

package taxes;

import java.util.*;
import java.io.*;

public class Taxes {

    public static void main(String[] args) throws IOException {
        //File aFile = new File("H:\\java\\PrimeNumbers\\build\\classes\\primenumbers\\priceList.txt");
        File aFile = new File("C:\\Users\\Tim\\Documents\\NetBeansProjects\\Taxes\\src\\taxes\\priceList.txt");
        priceChange(aFile);
    }

    static void priceChange(File inFile) throws IOException {
        Scanner scan = new Scanner("priceList.txt");
        char tab = '\t';
        while (scan.hasNextLine()) {
            String line = scan.nextLine();
            int a = line.indexOf(tab);
            String productName = line.substring(0,a);
            String priceTag = line.substring(a);
        }
    }
}

And here's the input:

Plyer set   10
Jaw Locking Plyers  10
Cable Cutter    7
16 oz. Hammer   5
64 oz. Dead Blow Hammer 12
Sledge Hammer   20
Cordless Drill  22
Hex Impact Driver 50
Drill Bit Set   30
Miter Saw   200
Circular Saw    40

回答1:


 Scanner scan = new Scanner("priceList.txt");

This line of code is wrong. This Scanner instance will scan the String "priceList.txt". It doesn't contain a tab, therefore indexOf returns -1.

Change it to:

 Scanner scan = new Scanner(inFile);

to use the method argument, that is the desired file instance of your priceList.txt.




回答2:


String.indexOf(char) will return -1 if an instance isn't found.

You need to check before proceeding that a isn't negative.

You can read more about the indexOf method here and here.




回答3:


Because you are checking int a = line.indexOf(tab) in every iteration of the while loop, there has to be a tab in every single line of your document in order for the error to be prevented. When your while (scan.hasNextLine()) loop runs into a line with no tab in it, the index is going to be -1, and you get the StringIndexOutOfBoundsException when trying to get line.substring(0,a), with a being -1.




回答4:


while (scan.hasNextLine()) {
    String line = scan.nextLine();
    int a = line.indexOf(tab);
    if(a!=-1) {
        String productName = line.substring(0,a);
        String priceTag = line.substring(a);
    }
}



回答5:


If you look very carefully at the input lines you have posted, you'll see

Jaw Locking Plyers  10
...
Cordless Drill  22
Hex Impact Driver 50
Drill Bit Set   30

that the "Hex Impact Driver" line has the price two characters to the right of the one in the lines before and after. This is an indication that "50" does not start at a tab position whereas "10" is at such a position, the next after the one for "22" and "30".

The Q&A editor does preserve TABs, so your editor preserves them as well, and your program should be able to recognize a TAB in the input lines.

That said, a TAB entered by hand (!) is a very poor choice for a separator. As you have experienced, text file presentation doesn't show it. It would be much better to use a special character that does not occur in the product names. Plausible choices are '|', '#', and '\'.

Another good way would be to use pattern matching to find the numeric price at the end of a line - the product name is what remains after removing the price and calling trim() on the remaining string.




回答6:


Since it has been verified that indexOf(tab) returns -1, the question is why does the line of text not contain t a tab when you seem certain that it does?

The answer is most likely the settings on your IDE. For instance, I usually configure Netbeans to convert a tab to three spaces. So if you typed this input file yourself within an IDE, the tab-to-space conversion is likely the problem.

Work around:

  1. If we copy/paste some text into Netbeans that includes tabs, the tabs do not get converted to spaces.
  2. The text file could be created with notepad or any other simple text editor to avoid the problem.
  3. Change the settings on your IDE, at least for this project.


来源:https://stackoverflow.com/questions/27761780/indexof-string-index-out-of-bounds-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!