Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

File Letter Counter, I'm getting 'character not found'

$
0
0
No matter what character I use, I keep getting 'character not found' when I try to use the code to search for it in a txt file.

import java.util.Scanner;//needed for Scanner Class
import java.io.*;//needed for input and output

public class FileLetterCounter
            
{
     public static void main(String[] args)
             throws IOException //begin main function
     {
         
         int count =0;
         String filename;
         String str;
         char character;
         Scanner keyboard = new Scanner(System.in);
         
         System.out.println("Enter a file name ");
         filename = keyboard.nextLine();
         
         System.out.println("Enter a character ");
         str = keyboard.nextLine();
         character = str.charAt(0);
         
         File file=new File(filename);
         Scanner inputFile=new Scanner(file);
         
         while(inputFile.hasNext())
         {
             String line=inputFile.nextLine();
             int len=line.length();
             for(int i=0;i<len;i++)
                 if (line.charAt(i) == character)
                     count++;
         }
         if(count <= 0)
         System.out.println("Character not found in the file");
         else
             System.out.println("Number of times character" +count+" in file");
         inputFile.close();
     }
     
}

Viewing all articles
Browse latest Browse all 51036

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>