2015-04-30 334 views
-1

分割功能不起作用。对于最后的打印声明,它给了我一个arrayoutofbound错误。任何帮助?while循环运行一次?

while (inFile.hasNext()) 
      { 
       String clean = inFile.nextLine(); 
       String[] nm = clean.split(","); 
       for (int i = 0; i < nm.length; i++) 
       { 
        System.out.println("at index "+ i +" string is "+nm[i]); 
       } 
       System.out.print("at index"+2+"Strin"+nm[3]); 
      } 

文本文件:

input1,2,3,4,5 
input2,2,3,4,5 
input3,3,4,5,6 
input4,3,4,5,6 
input5,3,4,5,6 

输出:

at index 0 string is input1 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 3 
    at filereader.FileReader.main(FileReader.java:33) 
Java Result: 1 
+0

使用'BufferReader'的'readLine()' –

+0

我运行它时没有遇到异常。 – ajb

+2

尝试添加'System.out.println(Arrays.toString(nm))'查看数组中的内容。如果该输出不能使问题清楚,那么编辑您的问题并添加输出。也许这会让我们知道还需要寻找什么。 – ajb

回答

1

的代码似乎是正确的,我和它不应该失败这个样子。唯一的原因,我可以看到的是,如果在你的输入文件中的空行,在这种情况下System.out.print("at index"+2+"Strin"+nm[3]);将在nm[3]

返回ArrayOutOfBoundException或者你可以写这样的代码:

while (inFile.hasNext()) 
     { 
      String clean = inFile.nextLine(); 
      if(clean != null && clean != ""){ 
      String[] nm = clean.split(","); 
      for (int i = 0; i < nm.length; i++) 
      { 
       System.out.println("at index "+ i +" string is "+nm[i]); 
      } 
      System.out.print("at index"+2+"Strin"+nm[3]); 
      } 
     } 

希望这个作品。

+0

仍然不起作用。我不知道为什么。 – DkgMarine

+0

错误的文件位置。感谢寿! – DkgMarine

1

这给了你错误:

System.out.print("at index"+2+"Strin"+nm[3]); 

这是因为你要么有一个空行或有不到4个逗号分隔项的行。尝试:

System.out.print("at index"+2+"Strin"+nm[nm.length-1]); 
1

也许纳米不具有4个元件的线

System.out.print("at index"+2+"Strin"+nm[3]); 

检查阵列含有至少4元件打印第四元件前的阵列。

// create a new scanner with the specified String Object 
    Scanner inFile = new Scanner(s); 
    while (inFile.hasNext()) 
    { 
     String clean = inFile.nextLine(); 
     String[] nm = clean.split(","); 
     for (int i = 0; i < nm.length; i++) 
     { 
      System.out.println("at index "+ i +" string is "+nm[i]); 
     } 
     if (nm.length > 3) { 
      System.out.print("at index"+2+"Strin"+nm[3]); 
     } 
     }