簡體   English   中英

Java StringIndexOutOfBoundsException

[英]Java StringIndexOutOfBoundsException

我正在編寫一個程序,該程序從文件“ items.txt”獲取輸入,並根據“ changes.txt”添加或刪除行,然后輸出到另一個文件。

這是“ items.txt”文件:

101,Nail #1
102,Nail #2
103,Nail #3
104,Hammer Small
105,Hammer Large

這是更改文件:

A,106,Chainsaw 12"
D,102
d,104
a,107,Chainsaw 10"

這是我的方法有問題( void changes()是行號132):

void changes() {
    try {
        fileChange = new Scanner(new File("changes.txt"));
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
    fileChange.useDelimiter(",|\r|\n");


    while (fileChange.hasNext()) {
        String codeStr = fileChange.next();
        if ((codeStr.charAt(0) == 'D') || (codeStr.charAt(0) == 'd')) {
            delete(fileChange.nextInt());
            System.out.println("delete");
        } else if ((codeStr.charAt(0) == 'A') || (codeStr.charAt(0) == 'a')) {
            add(fileChange.nextInt(), fileChange.next());
            System.out.println("add");
        } //else
            System.out.println("done");
    }

    fileChange.close();
}

這是我得到的輸出:

add
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 0
done

我在打印語句中添加了“添加”和“完成”,只是為了幫助更早地診斷問題。 即使它顯示“添加”和“完成”,也不會將任何內容發送到輸出文件。 我猜這是由於StringIndexOutOfBoundsException

這是我關於堆棧溢出的第一個問題,因此請耐心等待任何格式問題或禮節不當。

這樣做的原因是您將",|\\r|\\n"用作分隔符。 這將返回\\r\\n換行符之間的空令牌(假設您使用的是Windows風格的換行符)。 例如:

Scanner sc = new Scanner(new StringReader("Hello\r\nWorld"));
sc.useDelimiter(",|\r|\n");
while (sc.hasNext()) {
    String n = sc.next();
    System.out.println(n.length() + " " + n);
}

輸出:

5 Hello
0 
5 World

Ideone演示

因此,對於那些零長度的令牌,您不能讀取charAt(0) ,因為沒有這樣的字符。

將定界符更改為",|\\r\\n" ,即將\\r\\n視為單個定界符。

在執行charAt(0)之前,應先檢查codeStr.isEmpty() charAt(0)

您正在從一個空字符串訪問。

就像是

while (fileChange.hasNext()) {
    String codeStr = fileChange.next();
    if (codeStr.isEmpty()) continue;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM