java split异常,Java,split方法,抛出异常

Hello,

Could you please clarify why my code (part of it provided below) throws the following exception when I am trying to split my words from hints separated by a period in my text file:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0

at name.main(name.java:92) "92" corresponds to words.add(w[0]); in the code below:

File f = new File("name.txt");

Scanner fSc = new Scanner(f);

ArrayList words = new ArrayList();

ArrayList hints = new ArrayList();

while (fSc.hasNext())

{

String[] w = fSc.nextLine().split("."); // Split secret words from hints

words.add(w[0]);

hints.add(w[1]);

}

解决方案

This is because the array contains less elements than you assume. This exception on w[0] means that the string array is empty. If it was on w[1], it would mean that the array has less than 2 elements. If the array was null, exception would be different, null reference exception. Why it happened in your case? Use the debugger. In all cases, you cannot not assume certain array length, need to check it up before addressing by index.

—SA

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值