gpt4 book ai didi

java - 词频循环

转载 作者:行者123 更新时间:2023-12-01 12:40:22 25 4
gpt4 key购买 nike

此代码的目标是使用 main 方法 java 创建一个程序来分析用户输入的一段文本。

他们通过将文本输入扫描仪来做到这一点,然后由程序进行分析。分析的目的是产生词频、平均长度,并将结果以星号图的形式打印出来,单个“*”代表1个词。

例如“Birds can might Fly”应该输出以下结果:

Enter Text:
Birds can maybe fly
Birds can maybe fly
3 letter words: 2
5 letter words: 2
mean length: 4.0
3 letter words: **
5 letter words: **
Enter Text:

但是我得到了这个

Enter text: 
Birds can maybe fly
Birds can maybe fly
3 letter words: 2
3 letter words: *
mean lenght: 4.0
3 letter words: 2
3 letter words: **
mean lenght: 4.0
5 letter words: 2
5 letter words: *
mean lenght: 4.0
5 letter words: 2
5 letter words: **
mean lenght: 4.0
Enter text:

有没有办法改变我的代码,使其输出在第一部分中看到的内容,而不是我在第二部分中得到的内容。

代码:

import java.util.Scanner;

public class Freq
{

public static void main(String[] args)
{

Scanner scan = new Scanner(System.in);

while (true)
{

System.out.println("Enter text: ");

String s;
s = scan.nextLine();
String input = s;
String strippedInput = input.replaceAll("\\W", " ");

System.out.println("" + strippedInput);

String[] strings = strippedInput.split(" ");
int[] counts = new int[6];
int total = 0;

for (String str : strings)
if (str.length() < counts.length)
counts[str.length()] += 1;
for (String s1 : strings)
total += s1.length();

for (int i = 1; i < counts.length; i++){
StringBuilder sb = new StringBuilder(i).append(i + " letter words: ");
for (int j = 1; j <= counts[i]; j++) {


sb.append('*');
System.out.println(i + " letter words: " + counts[i]);
System.out.println(sb);
System.out.println(("mean lenght: ") + ((double) total / strings.length));


}}}}}

最佳答案

你的循环是混合的,所以你打印了太多的东西,而且有时在错误的时间打印。您应该拆分循环。

首先,您只想按长度输出计数:

for (int i = 1; i < counts.length; i++){    
System.out.println(i + " letter words: " + counts[i]);
}

然后你想输出平均长度:

System.out.println(("mean length: ") + ((double) total / strings.length));

最后你想输出星号:

for (int i = 1; i < counts.length; i++){    
StringBuilder sb = new StringBuilder(20);
sb.append(i);
sb.append(" letter words: ");
for (int j = 1; j <= counts[i]; j++) {
sb.append('*');
}
System.out.println(sb);
}

关于java - 词频循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25162905/

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