NoSuchElementException in - Java

时间:2016-01-29 11:55:21

标签: java combobox nosuchelementexception

我正在尝试从文本文件中读取数据,然后将其存储到数组中。我假设每行有一个单词。我在这里得到NoSuchElementException

while (s.hasNextLine()) 
       {
           text = text + s.next() + " ";
       }

这是我的代码:

public class ReadNote 
{
   public static void main(String[]args) 
   { 


      String text = readString("CountryList.txt");
      System.out.println(text);

      String[] words = readArray("CountryList.txt");

      for (int i = 0; i < words.length; i++) 
      {
         System.out.println(words[i]);
      }
}


  public static String readString(String file) 
  {

       String text = "";

       try{
       Scanner s = new Scanner(new File(file));

       while (s.hasNextLine()) 
       {
           text = text + s.next() + " ";
       }

         } catch(FileNotFoundException e) 
           {
              System.out.println("file not found ");
           }
        return text;
   }


  public static String[] readArray(String file) 
  { 
      int ctr = 0;

       try {
       Scanner s1 = new Scanner(new File(file));

       while (s1.hasNextLine()) 
       {
            ctr = ctr+1;
            s1.next();
       }

       String[] words = new String[ctr];
       Scanner s2 = new Scanner(new File(file));

       for ( int i = 0; i < ctr; i++) 
       {
           words [i] = s2.next();
       }

        return words;

    } catch (FileNotFoundException e) { }
        return null;
 }
}

这是消息。

    Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Scanner.java:862)
    at java.util.Scanner.next(Scanner.java:1371)
    at ReadNote.readString(ReadNote.java:29)
    at ReadNote.main(ReadNote.java:13)

3 个答案:

答案 0 :(得分:0)

据我所知,您的代码存在 2 问题:

  • 您忘了查看hasNextLine()第二个Scanner s2 使用Scanner时,您需要检查下一行是否有hasNextLine(),并且会在null返回EOF
  • 您可能希望在s.nextLine()循环中s.next()代替while,因为您正在检查while (s1.hasNextLine())。一般情况下,您必须.hasNext....next...匹配。

答案 1 :(得分:0)

针对readString中的特定例外:

while (s.hasNextLine()) {
  text = text + s.next() + " ";
}

您需要在循环保护中调用s.hasNext(),或在正文中使用s.nextLine()

答案 2 :(得分:0)

this answer中所述。

您的文件末尾只有一个额外的换行符。

hasNextLine()检查缓冲区中是否还有另一个linePattern。 hasNext()检查缓冲区中是否存在可解析的令牌,由扫描程序的分隔符分隔。

您应该将代码修改为以下之一

while (s.hasNext()) {
    text = text + s.next() + " ";
}

while (s.hasNextLine()) {
    text = text + s.nextLine() + " ";
}