gpt4 book ai didi

java - 我需要计算文本文档的总字数、每行平均字数和每行元音

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:18:12 24 4
gpt4 key购买 nike

我是 java 的新手,对我正在处理的程序有疑问。该程序的主要思想是给定一个文档,计算文档中的单词总数、每行的平均单词数和每行的元音。我想出了一个起点,但真的不知道如何继续。

import java.io.*;

public class Example {
public static void main(String[] args) throws IOException {
int vowelCount = 0, wordsAvg = 0, wordsCount = 0, a;
char ch;
String line;
int vowels1 = 0, vowels2 = 0, vowels3 = 0, vowels4 = 0, vowels5 = 0, vowels6 = 0, vowels7 = 0, vowels8 = 0, vowels9 = 0, vowels10 = 0;
BufferedReader in ;

in = new BufferedReader(new FileReader("message.txt"));

line = in .readLine();
}
for (int i = 0; i < line.length(); i++) {
ch = line.charAt(i);

if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') vowels1++;
}

{
System.out.println(line);
System.out.println("--------------------------------------------");
System.out.println("Total number of words: " + wordsCount);
System.out.println("Average number of words per line: " + wordsAvg);
System.out.println("The number of vowels in line 1 is: " + vowels1);
System.out.println("The number of vowels in line 2 is: " + vowels2);
System.out.println("The number of vowels in line 3 is: " + vowels3);
System.out.println("The number of vowels in line 4 is: " + vowels4);
System.out.println("The number of vowels in line 5 is: " + vowels5);
System.out.println("The number of vowels in line 6 is: " + vowels6);
System.out.println("The number of vowels in line 7 is: " + vowels7);
System.out.println("The number of vowels in line 8 is: " + vowels8);
System.out.println("The number of vowels in line 9 is: " + vowels9);
System.out.println("The number of vowels in line 10 is: " + vowels10);
line = in .readLine();
}
}

到目前为止,我已经让程序读取文件并计算第一行的元音,但我真的不知道如何遍历每一行。我还需要显示输出,因为我已经预先设置好了。感谢任何帮助,尽量保持简单会很好。

最佳答案

您可以使用 BufferedReader 在 java 中读取文件,直到 line 不为空。在读取文件时,您可以调用适当的方法来计算单词、元音等的数量 -

BufferedReader br = new BufferedReader(new FileReader("file.txt"));
try {

String line = br.readLine();

while (line != null) {
int wordsPerLine = countWord(line);
int vowelsPerLine = countVowel(line);

line = br.readLine();
}

} finally {
br.close();
}

现在您可以像这样编写您的 countWord(String line) 方法 -

//this method will count word for per input line
public int countWords(String line)
{
String words[]=line.split(" ");
int count=words.length;
return count;
}

你也可以像这样计算每行的元音 -

public int coutnVowels(String line){

int count =0;
for(int i=0; i<line.length; i++){

char currentChar = line.CharAt(i);
if(currentChar=='a'||currentChar=='e'||currentChar=='i'||currentChar=='o'
currentChar=='u'){

count++;
}
}

return count;
}

关于java - 我需要计算文本文档的总字数、每行平均字数和每行元音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30336929/

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