此代码的目标是使用main方法java创建一个程序来分析从用户输入的文本文本。
他们通过将文本输入扫描仪来执行此操作,然后由程序进行分析。分析是产生单词频率,平均长度,并以星号图表的形式打印出结果,是单个" *"代表1个单词。
例如"鸟类可能会飞#34;应该输出这个结果:
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));
}}}}}
答案 0 :(得分:1)
你的循环是混合的,所以你打印的东西太多了,有时是在错误的时间。你应该分开你的循环。
首先,您只想按长度输出计数:
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);
}