我编写了一个程序来计算.txt文件中某个字母的数量,但是我不断收到一条错误消息,指出FileNotFoundException无法解析为一种类型。这是我的代码。

import java.util.Scanner;
import java.io.File;
import java.io.IOException;
import java.io.BufferedReader;

public class Count
{
  public static void main (String[] args) throws FileNotFoundException {

      String phrase;    // a string of characters
      int countBlank;   // the number of blanks (spaces) in the phrase
      int length;       // the length of the phrase
      char ch;          // an individual character in the string
  int countA;
  int countE;
  int countS;
  int countT;

  java.io.File file = new java.io.File("counting.txt");
  Scanner inFile = new Scanner (file);

 Scanner scan = new Scanner(System.in);

      phrase = scan.nextLine();
      length = phrase.length();

      // Initialize counts

  while (true)
  {
  if (phrase.equalsIgnoreCase("quit"))

      break;

  else
  {

  countBlank = 0;
  countA = 0;
  countE = 0;
  countS = 0;
  countT = 0;

  for ( int i = 0; i < length; i++ )
   {
   if ( phrase.charAt( i ) == ' ' )

    countBlank++;
    ch = phrase.charAt(i);

       switch (ch)
        {
         case 'a':
         case 'A':  countA++;
                 break;
     case 'e':
     case 'E':  countE++;
         break;
     case 's':
     case 'S':  countS++;
            break;
     case 't':
     case 'T':  countT++;
        break;
      }

 }


    System.out.println ();
        System.out.println ("Number of blank spaces: " + countBlank);
        System.out.println ();

    System.out.println ("Number of A's: " + countA);
    System.out.println ();
    System.out.println ("Number of E's: " + countE);
    System.out.println ();
    System.out.println ("Number of S's: " + countS);
    System.out.println ();
    System.out.println ("Number of T's: " + countT);
    break;
  }
 }
 }
}

最佳答案

您缺少FileNotFoundException的导入,可以这样添加它-

import java.io.FileNotFoundException;


或者,您可能希望使用通配符导入整个java.io软件包

import java.io.*;


许多IDE可以搜索导入[和/或]自动完成,只需转到单词FileNotFoundException的末尾并尝试按CTRL-SPACE

关于java - 尝试在Java中读取.txt文件时,无法将FileNotFoundException解析为一种类型,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21080408/

10-12 14:18