"Счетчик букв файла:
Напишите программу, которая запрашивает у пользователя введите имя файла, а затем предложит пользователю ввести символ. Программа должна подсчитать и отобразить количество раз, которое указанный символ появляется в файле. Используйте Блокнот или другой текстовый редактор, чтобы создать образец файла, который можно использовать. использовался для тестирования программы."
Текстовый файл, который мой профессор предоставил нам для тестирования этой программы, содержит 1307 строк случайных букв, расположенных в этой программе. пройти, и по какой-то причине я не могу заставить эту программу работать правильно. Я пробовал использовать вещи, выходящие за рамки того, что мы уже узнали на уроке и в книге, но я совершенно запутался.
Пример ввода:
Код: Выделить всё
f
d
s
h
j
Код: Выделить всё
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);
/*
My dad, after looking at my code, said (and I'm paraphrasing)
it's basically doing a JD Vance. Is there a line? "Okay, good.
It might not even be checking for other lines, it might be
repeatedly iterating over the same line.
I almost died because of his meme comparison.
*/
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();
}
}
Код: Выделить всё
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.
Код: Выделить всё
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)
Код: Выделить всё
Enter the file name: "filename"
Enter a character: "character"
The character (character) appears (number of times) times in the file.
Изменить:[/b]
Я решил свою проблему проблема и программа заработала. Если по какой-либо причине кому-то в будущем понадобится такое решение, я опубликую имеющийся у меня код, который сейчас работает как задумано (с некоторыми добавленными комментариями):
Код: Выделить всё
package filelettercounter;
import java.util.Scanner;
import java.io.*;
public class FileLetterCounter {
public static void main(String[] args) throws IOException, FileNotFoundException{
File file;
Scanner fileScanner;
String filename;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter file name: ");
filename = keyboard.nextLine();
//I needed to store the character value BEFORE
//switching to the File Scanner.
System.out.print("Enter a character: ");
String character = keyboard.nextLine();
file = new File(filename);
if(!file.exists()) {
System.out.println("The file does not exist.");
System.exit(0);
}
fileScanner = new Scanner(file);
if(!fileScanner.hasNextInt()) {
System.out.println("Error with file structure.");
System.exit(0);
}
/*
I didn't need the do-while loop, either. At the time of
the original code, I was throwing things into the code to
see what would work and crossing my fingers.
It took me a while to figure this part out, as well.
I didn't think having an int variable and a separate
String variable would work as intended, but it worked
(don't ask me why I thought this, I just did).
*/
int lines = fileScanner.nextInt();
fileScanner.nextLine();
int counter = 0;
for(int i = 0; i < lines; i++) {
String line = fileScanner.nextLine();
if(line.contains(character) && character.equalsIgnoreCase(character)) {
counter++;
}
}
System.out.println("The character " + character + " appears " + counter
+ " times.");
}
}
Подробнее здесь: https://stackoverflow.com/questions/790 ... -file-in-j
Мобильная версия