gpt4 book ai didi

java - Java从文件中扫描每个字符

转载 作者:行者123 更新时间:2023-12-02 04:49:36 24 4
gpt4 key购买 nike

我有一个程序可以扫描文本文件并识别每行是否以元音开头,但是,我需要能够扫描每个字符以确定该行上是否有元音,而不仅仅是在开始时。

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 但我没有运气,所以我想也许我的错误很小,这里有人可以帮助我吗?

最佳答案

这个问题似乎有点令人困惑,但如果您试图在文件中查找元音,您可以逐行执行。下面是一些示例代码:

    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++;
}
}
}

我想如果你想计算以元音开头的行数,你可以添加一个 if 语句,当 i 为零且它是元音时。

关于java - Java从文件中扫描每个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29349685/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com