我有一个扫描文本文件并识别每行是否以元音开头的程序,但是,我需要能够扫描每个字符以确定该行上是否有元音而不仅仅是在开始时。
String x = "";
Set<String> vowells = new HashSet<>();
vowells.add("a");
vowells.add("e");
vowells.add("i");
vowells.add("o");
vowells.add("u");
while (sc.hasNextLine()) {
readLine = new Scanner(sc.nextLine());
x = readLine.nextLine();
numberOfLines++;
if(vowells.contains(x.toLowerCase())) {
numberOfVowells++;
}
}
我尝试过使用while sc.hasNext
并尝试使用splitregex,但我没有运气,所以我想也许我的错误很小,有人可以帮我吗?
答案 0 :(得分:2)
这个问题似乎有些令人困惑,但如果你想在文件中找到元音,你可以逐行进行。这是一些示例代码:
int numberOfVowells = 0;
String x = "";
String letter = "";
Set<String> vowells = new HashSet<>();
vowells.add("a");
vowells.add("e");
vowells.add("i");
vowells.add("o");
vowells.add("u");
File myFile = new File("Hello.txt");
Scanner sc = new Scanner(myFile);
while(sc.hasNextLine())
{
//take it in line by line
x = sc.nextLine();
//cycle through each character in the line
for(int i = 0; i < x.length(); i++)
{
letter = x.substring(i,i);
if(vowells.contains(letter.toLowerCase()))
{
numberOfVowells++;
}
}
}
我想如果你想计算以元音开头的行数,你可以在i为零时添加一个if语句,它是一个元音。
答案 1 :(得分:1)
您只需使用一个Scanner
即可阅读该文件。
File file = new File("the/path/to/your/file");
Scanner scanner = new Scanner(file);
然后您可以使用hasNextLine()
和nextLine()
逐行阅读文件内容
String currLine;
while(scanner.hasNextLine()) {
currLine = scanner.nextLine();
//do something with currLine
}
在你的情况下似乎你想检查当前行是否以元音开头,所以我建议先将currLine
全部小写并修剪。
currLine = currLine.toLowerCase().trim();
然后您可以使用startsWith
和charAt
等字符串函数进行检查。
答案 2 :(得分:-1)
Scanner filescan = new Scanner(new File("**your document/file**"));