简体   繁体   English

IndexOf(),字符串索引超出范围:-1

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

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. 当我使用indexOf()查找选项卡时,出现String index out of bounds error ,它说index是-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
 Scanner scan = new Scanner("priceList.txt");

This line of code is wrong. 这行代码是错误的。 This Scanner instance will scan the String "priceList.txt" . 该Scanner实例将扫描字符串"priceList.txt" It doesn't contain a tab, therefore indexOf returns -1 . 它不包含标签,因此indexOf返回-1

Change it to: 更改为:

 Scanner scan = new Scanner(inFile);

to use the method argument, that is the desired file instance of your priceList.txt . 使用method参数,即priceList.txt的所需文件实例。

String.indexOf(char) will return -1 if an instance isn't found. 如果找不到实例,则String.indexOf(char)将返回-1。

You need to check before proceeding that a isn't negative. 您需要先检查a是否为负值。

You can read more about the indexOf method here and here . 您可以在此处此处阅读有关indexOf方法的更多信息。

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. 因为您在while循环的每次迭代中都检查int a = line.indexOf(tab) ,所以文档的每一行中都必须有一个制表符 ,以防止错误发生。 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. 当您的while (scan.hasNextLine())循环碰到没有选项卡的行时,索引将为-1,并且在尝试获取line.substring(0,a)时,您会收到StringIndexOutOfBoundsException ,其中a为-1。

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

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. 则“ Hex Impact驱动程序”行的价格在前后各行的右边两个字符。 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". 这表示“ 50”不是在制表符位置开始,而“ 10”是在这样的位置,紧接在“ 22”和“ 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. 问与答编辑器的确会保留TAB,因此您的编辑器也会保留它们,并且您的程序应该能够在输入行中识别TAB。

That said, a TAB entered by hand (!) is a very poor choice for a separator. 就是说,手动输入(!)的TAB对于分隔符来说是一个很差的选择。 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. 另一个好方法是使用模式匹配在行尾查找数字价格-产品名称是删除价格并在剩余字符串上调用trim()之后剩下的名称。

Since it has been verified that indexOf(tab) returns -1, the question is why does the line of text not contain ta tab when you seem certain that it does? 由于已经验证indexOf(tab)返回-1,因此问题是,为什么在您确定行的文本行中不包含ta tab

The answer is most likely the settings on your IDE. 答案很可能是IDE上的设置。 For instance, I usually configure Netbeans to convert a tab to three spaces. 例如,我通常将Netbeans配置为将选项卡转换为三个空格。 So if you typed this input file yourself within an IDE, the tab-to-space conversion is likely the problem. 因此,如果您在IDE中自己输入了此输入文件,则可能是制表符到空格的转换。 Netbeans编辑器选项对话框

Work around: 解决:

  1. If we copy/paste some text into Netbeans that includes tabs, the tabs do not get converted to spaces. 如果我们将一些包含制表符的文本复制/粘贴到Netbeans中,则制表符不会转换为空格。
  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. 至少在此项目上更改IDE上的设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM