【问题标题】:Getting ArrayIndexOutOfBound when using line.split on the string在字符串上使用 line.split 时获取 ArrayIndexOutOfBound
【发布时间】:2013-12-05 00:38:19
【问题描述】:

获取 indexOutOfBound。成功保存文件后。我打开文件执行以下任务:找到总costPerItem、totalCount 和sum。不知道为什么我越界了。错误指出

totalCost =+ Double.parseDouble(index[1].trim());

源代码:

 Scanner data = new Scanner(new File("registryCopy.txt"));

    while(data.hasNext()){
        String line = data.nextLine();
        System.out.println(line);

        String[] index = line.split("\\t");
        totalCost += Double.parseDouble(index[1].trim());
        totalCount += Integer.parseInt(index[2].trim());

        sum = totalCost/totalCount;

    }

错误

Error: "main" java.lang.ArrayIndexOutOfBoundsException: 1 

即:totalCost += Double.parseDouble(index[1].trim());

由于某些原因,它不会拆分行。文本文件如下:

item1 15.00 3
item2 15 2
item3 14 3

文件是之前创建的,并提示用户输入该数据。来源:

while(userInput.charAt(0)!='n'){
        /**
         * Need only one PrintWriter out0 i.e, then I either use the userbased name OR fixed name creation i.e registryCopy.txt(true will
         * not overwrite the file but go to the next).
         */
        PrintWriter out0 = new PrintWriter(new BufferedWriter(new FileWriter("registryCopy.txt", true)));

    System.out.print("Enter item name: ");
    itemName = kybd.next();//user String
    out0.print(itemName + " ");

    System.out.print("Enter item price: $");
    price = kybd.next();
    out0.print(price + " ");

    System.out.print("Enter item quantity: ");
    quantity = kybd.next();
    out0.println(quantity);


    System.out.print("Do you have another item to scan? Yes(y) or No(n): ");
    userInput= kybd.next();
    out0.flush();
    }//end of whileLoop

Update1:​​你们太棒了,\s 成功了。当你在芝加哥时,请给我啤酒。谢谢

输出源代码:

sum = totalCost*totalCount;
    System.out.println("");
    System.out.println(totalCost);
    System.out.println(totalCount);
    System.out.println(sum);

标准操作程序:

项目1 15.00 3

项目2 15 2

项目3 14 3

项目5 10.00 3

项目 5 12

bla 11 5

面包 1 15

项目14 5 3

76.0

46

3496.0

【问题讨论】:

  • 欢迎来到 SO。对于包含所有必要信息的问题 +1 :-)

标签: java file-io io


【解决方案1】:

您对split 的调用在标签上拆分;您的输入似乎有一些其他类型的空格分隔标记。

要拆分任何类型的空格,请使用"\\s"

String[] index = line.split("\\s");

\s 是一个regular expression,代表以下任何一种:' ', '\t', '\n', '\x0B', '\f', '\r'

【讨论】:

    【解决方案2】:

    编写文件的程序在字段之间放置空格字符。读取文件的程序试图在制表符上分割行,而不是空格。你有两个选择。

    1. 更改写入文件的程序,使其插入制表符 - 即,在源代码中有+ " " 的任何位置,将其更改为+ "\t"
    2. 更改读取文件的程序,以便在空格字符上分割行。也就是说,将其设为line.split(" ")。或者,您可以使用line.split("\\s"),它将在任何类型的空白处分割。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-03
      • 2013-10-24
      • 1970-01-01
      • 2017-03-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多