I'm having trouble writing a program for my Java class. The assignment's instructions are as follows:
"File Letter Counter:
Write a program that asks the user to enter the name of a file, and then asks the user to enter a character. The program should count and display the number of times that the specified character appears in the file. Use Notepad or another text editor to create a sample file that can be used to test the program."
The text file my professor provided us to test this program has 1307 lines of randomly cased and placed letters that this program has to go through and, for whatever reason, I can't seem to get this program to work right. I've tried using things outside of what we've learned so far in class and in the book, but I'm beyond lost.
Sample input:
f
d
s
h
j
Here's my code so far (compiled in NetBeans 23):
package filelettercounter;
import java.util.Scanner;
import java.io.*;
public class FileLetterCounter {
public static void main(String[] args) throws IOException {
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the file name: ");
String filename = keyboard.nextLine();
File file = new File(filename);
Scanner inputFile = new Scanner(file);
do {
int counter = 0;
String line = inputFile.nextLine();
System.out.print("Enter a character: ");
String character = inputFile.nextLine();
if(line.contains(character)) {
counter++;
}
System.out.println("The character " + character + " appears " +
counter + " times in the file.");
}while(inputFile.hasNext());
inputFile.close();
}
}
The output prints all 1307 lines showing that they each appear 0 times...
Enter a character: The character f appears 0 times in the file.
Enter a character: The character d appears 0 times in the file.
Enter a character: The character s appears 0 times in the file.
Enter a character: The character h appears 0 times in the file.
Enter a character: The character j appears 0 times in the file.
...with an exception thrown most of the way down the output.
Exception in thread "main" java.util.NoSuchElementException: No line found
at java.base/java.util.Scanner.nextLine(Scanner.java:1660)
at filelettercounter.FileLetterCounter.main(FileLetterCounter.java:31)
The output I need to achieve is something like this:
Enter the file name: "filename"
Enter a character: "character"
The character (character) appears (number of times) times in the file.
Regarding input from any of you who are infinitely more experienced than I am, I'm not supposed to be doing anything fancy. The farthest we've gotten through as a class has been the various loops (for, if/else if/else, do-while, while), accumulating variables, etc. It is as basic as basic gets. So, please no lists or arrays or delimiters, or anything crazy like that.