请教一下高手,用JAVA编写一个程序能统计每个长度的单词的数量!!
发布网友
发布时间:2023-12-05 01:06
我来回答
共3个回答
热心网友
时间:2024-12-13 05:27
import java.util.Arrays;
import java.util.Scanner;
import java.util.StringTokenizer;
public class Test {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String str = scan.nextLine();
StringTokenizer st = new StringTokenizer(str, " ");
int total = st.countTokens();
int len[] = new int[20];
Arrays.fill(len, 0);
while (st.hasMoreTokens()) {
String s = st.nextToken();
len[s.length()]++;
}
System.out.println("长度 个数");
int max = 1;
for (int i = 1; i < len.length; i++) {
if (len[i] > 0)
max = i;
}
for (int i = 1; i <= max; i++) {
System.out.printf("%-8d%d\n", i, len[i]);
}
System.out.println("-----------------");
System.out.println("合计: " + total);
}
}
热心网友
时间:2024-12-13 05:28
package org.skyway..;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
public class Calc {
public static void main(String args[]) {
Scanner cin = new Scanner(System.in);
String input = cin.nextLine();
String[] words = input.split(" ");
Map<Integer, Integer> calc = new HashMap<Integer, Integer>();
for (String word : words) {
int length = word.length();
if (calc.containsKey(length)) {
int number = calc.get(length);
calc.put(length, 1 + number);
} else {
calc.put(length, 1);
}
}
Set<Integer> keys = calc.keySet();
List<Integer> length = new ArrayList<Integer>(keys);
Collections.sort(length);
for (int i = 1; i < length.get(length.size() - 1); i++) {
System.out.println(i + "\t" + (calc.get(i) == null ? 0 : calc.get(i)));
}
}
}
热心网友
时间:2024-12-13 05:28
你可以用StringTokenizer 类,用该类创建的对象调用方法nextTokens(),该对象是一个字符串分析器,方法countTokens()返回字符串的长度,hasMoreCode()方法返回字符是否分析完,你试试
java学习交流群 194252842