在字符串上使用line.split时获取ArrayIndexOutOfBound

 手机用户2602890535 发布于 2023-02-12 18:47

获取indexOutOfBound.成功保存文件后.我打开文件来执行以下任务:找到total 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做了伎俩.当你在芝加哥的时候喝啤酒.谢谢

OUTPUT sourceCode:

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

SOP:

item1 15.00 3

item2 15 2

item3 14 3

item5 10.00 3

项目5 12

bla 11 5

面包1 15

item14 5 3

76.0

46

3496.0

1 个回答
  • split对标签上的拆分的调用; 看来您的输入有一些其他类型的空格分隔标记.

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

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

    \s是一个正则表达式,代表以下任何一种:' ', '\t', '\n', '\x0B', '\f', '\r'.

    2023-02-12 18:49 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有