【问题标题】:I keep getting the java.util.NoSuchElementException but I do not see where the error lies我不断收到 java.util.NoSuchElementException 但我看不到错误在哪里
【发布时间】:2021-09-14 20:53:33
【问题描述】:

我正在尝试编写一个读取文本文件并计算每个单词出现次数的 java 程序。但我不断收到没有这样的元素异常。我认为 ArrayList 或者我如何访问它的元素有问题。任何帮助将不胜感激。


    package text_analyzer;
import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.util.List;

public class Text_analyzer
{
  public static void main(String[] args) throws Exception
  {
        File file = new File("TestFile.txt");

        Scanner sc = new Scanner(file);
        int i = 0, indexOfWord = 0, count = 0;
        List<String> words = new ArrayList<String>();
        List<Integer> wordCount = new ArrayList<Integer>();
 
        while (sc.hasNextLine())
        {
         String word = sc.next();
    
          if(words.contains(word))
          {
          indexOfWord = words.indexOf(word);
          count = wordCount.get(indexOfWord);
          count = count+1;
          wordCount.add(indexOfWord, count);        
          }
          else
          {
          words.add(i,word);
          wordCount.add(i,1);
          i++;
          }
         }
                  
        sc.close();
        
        int no_of_elements = words.size();
        for(int j = 0; j < no_of_elements; j++)
            System.out.println(words.get(j));
  }
 }


【问题讨论】:

  • 如果你使用hasNextLine,你应该使用nextLine,而不是next
  • 哇,立即工作。谢谢。

标签: java nosuchelementexception


【解决方案1】:

你的逻辑是正确的

  1. 检查文件的路径,并确保它存在或添加额外的签入代码。 File Path

  2. 为新的 File() 方法添加异常处理,以防找不到文件。

     File file = new File("C:\\work\\TestFile.txt");
    
     Scanner sc = null;
     try {
         sc = new Scanner(file);
     } catch (FileNotFoundException e) {
         e.printStackTrace();
     }
    

结果:Output result

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-14
    • 1970-01-01
    相关资源
    最近更新 更多