Java,split方法,抛出异常 [英] Java, split method, throws Exception

查看:421
本文介绍了Java,split方法,抛出异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

您能否澄清一下为什么我的代码(下面提供的部分代码)在我尝试将文字文件中的句点分隔的提示分开时会引发以下异常:



线程main中的异常java.lang.ArrayIndexOutOfBoundsException:0

at name.main(name.java:92)92 对应于words.add(w [0]);在下面的代码中:





文件f =新文件(name.txt);

扫描仪fSc =新扫描仪(f);

ArrayList< string> words = new ArrayList< string>();

ArrayList< string> hints = new ArrayList< string>();

while(fSc.hasNext())

{

String [] w = fSc.nextLine()。split(。) ; //从提示中拆分秘密词

words.add(w [0]);

hints.add(w [1]);

}

解决方案

这是因为数组包含的元素少于您所假设的元素。 w [0] 上的此异常表示字符串数组为空。如果它在 w [1] 上,则意味着该数组少于2个元素。如果数组为null,则异常将不同,null引用异常。为什么它发生在你的情况下?使用调试器。在所有情况下,您都不能假设某些数组长度,需要在通过索引寻址之前进行检查。



-SA

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<string> words = new ArrayList<string>();
ArrayList<string> hints = new ArrayList<string>();
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


这篇关于Java,split方法,抛出异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆