gpt4 book ai didi

java - 读取一个文件,统计元音(字符) "aeiou"依次出现了多少次

转载 作者:行者123 更新时间:2023-11-30 10:53:21 24 4
gpt4 key购买 nike

它忽略辅音。它忽略任何类型的空间。它忽略大小写。唯一不能忽略的是另一个元音出现顺序不正确。

这些计数:

AEIOU,
aeiou,
hahehihohu,
Take it out

这些不:

AEIuO,
Taco is good,
Take it over

这是我目前所拥有的:

import java.util.Scanner;

public class AEIOU_Counter {

public static void main(String[] args) throws Exception {
java.io.File file = new java.io.File("vowels.txt");

Scanner input = new Scanner(file);
String fileContent = "";
while (input.hasNext())
{
fileContent += input.next() + " ";
}
input.close();

char[] charArr = fileContent.toCharArray();
int counter = 0;
for (char c : charArr)
{
if(c == 'a' || c == 'e' ||c == 'i' ||c == 'o' ||c == 'u')
counter++;
}
System.out.println("The file " + file + " has AEIOU in order " + counter + " times");
}
}

问题是输出:文件 vowels.txt 有 AEIOU 顺序 50 次

但是,文件 vowels.txt 包含:

AEIOU aeiou baeiboeu bbbaaaaaa beaeiou caeuoi ajejijoju aeioo 
aeiOu ma me mi mo mu take it OUT!

所以正确的输出应该是:

文件 vowels.txt 有 8 次 AEIOU

最佳答案

我可以想到两种方法。没有真正的代码,因为这是你的任务:)

第一种方法是将输入编辑得尽可能简单。

1. Read input from file
2. toLowerCase() the input (to make "aEiOU" simplar as just "aeiou")
3. Remove all non-vowel characters. (so that 'hahehihohu' becomes 'aeiou')
4. Search for literal string "aeiou" and count occurrances.

第二种方法是单独保留输入,但使用循环和计数器。 “序列”可以是数组,也可以是链表

sequence = [a,e,i,o,u] // (or a->e->i->o->u)
curr_char_of_sequence = 'a'
counter = 0

for each char in the input, loop {
if the char is not a vowel {
continue to next char
}

//see if the vowel is the one we want next
if char == curr_char_of_sequence {
//it is! update whats the next vowel we want.
// ie, if we were looking for an 'a', now look for an 'e'
curr_char_of_sequence = sequence.next

//check to see if we reached the end of the sequence, if so, we found a completed 'aeiou' set
if curr_char_of_sequence == invalid {
counter++
curr_char_of_sequence = 'a'
}

//we found a vowel that isn't the right one, restart the sequence
} else {
curr_char_of_sequence = 'a'
}
}

关于java - 读取一个文件,统计元音(字符) "aeiou"依次出现了多少次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34030482/

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