【发布时间】:2020-10-30 20:05:35
【问题描述】:
我正在尝试创建一个程序来读取 txt 文档并计算用户输入的字母的出现次数。似乎我索引字母的 for 循环不正确,因为它只读取文档的第一行或最后一行。有什么想法吗?
txt文件包含:
Porsche GT2 RS
Lamborghini Huracan Evo
Mercedes Benz S 63 AMG
Merces Benz AMG GT 63s
Ferrari F8 Tributo
程序如下:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;
public class GetOccurChar {
static void GetOccurFile(File f) throws IOException {
System.out.println("What letter do you want to check the occurence for in the file?");
Scanner scan2 = new Scanner(System.in);
char c = scan2.next().charAt(0);
int count = 0;
String str= "";
char[] ch = new char[100];
try {
Scanner scan = new Scanner (f);
while (scan.hasNextLine()) {
str = scan.nextLine().toLowerCase();
for (int i = 0; i < str.length(); i++)
ch[i] = str.charAt(i);
}
scan.close();
for (int i = 0; i < ch.length; i++)
if (ch[i] == c)
count++;
System.out.println(c +" occures " + count + " times in the file.");
System.out.println(ch);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
输出:
What letter do you want to check the occurence for in the file?
t
t occures 2 times in the file.
ferrari f8 tributo 63so
【问题讨论】:
标签: java arrays java.util.scanner find-occurrences