Java 计数';x';字母词
我现在有这个代码,例如,如果我输入单词“你好”,它将输出“3”,但是我想编辑我的代码,使其输出有3个字母单词,我怎么做Java 计数';x';字母词,java,string,Java,String,我现在有这个代码,例如,如果我输入单词“你好”,它将输出“3”,但是我想编辑我的代码,使其输出有3个字母单词,我怎么做 import java.util.*; public final class CountLetters { public static void main (String[] args) { Scanner sc = new Scanner(System.in); String words = sc.nextLine
import java.util.*;
public final class CountLetters {
public static void main (String[] args) {
Scanner sc = new Scanner(System.in);
String words = sc.nextLine();
String[] letters = words.split(" ");
for (String str1 : letters)
{
System.out.println(str1.length() );
}
}
}
添加一个
int
s数组以跟踪每个字长的计数
对于每个单词,增加数组中与单词长度对应的值
最后,检查int数组并打印出找到的每种长度的单词数。对于这一步,您应该添加一个条件,使其仅在计数大于0时打印。您可以为此使用哈希映射
public static void main(String[]args){
Scanner input = new Scanner(System.in);
String bubba = input.nextLine();
Map<Integer,Integer> occurrences = new HashMap<Integer,Integer>();
for(String currentWord: bubba.split(" ")){
Integer current = occurrences.get(currentWord.length());
if(current==null){
current = 0;
}
occurrences.put(currentWord.length(), current+1);
}
for(Integer currentKey: occurrences.keySet()){
System.out.println("There are "+occurrences.get(currentKey)+" "+currentKey+" letter words");
}
}
publicstaticvoidmain(字符串[]args){
扫描仪输入=新扫描仪(System.in);
字符串bubba=input.nextLine();
映射出现次数=新建HashMap();
for(字符串currentWord:bubba.split(“”){
整数current=executions.get(currentWord.length());
如果(当前==null){
电流=0;
}
put(currentWord.length(),current+1);
}
for(整数currentKey:executions.keySet()){
System.out.println(“存在”+出现次数.get(currentKey)+“+currentKey+”字母词”);
}
}
如果您从输入中知道可能的最长字长,请将其作为数组大小。如果没有,您可以读取输入两次,一次确定最长的单词,然后第二次计算所有长度。第三种选择是使用映射,其中键是单词长度,值是单词长度的计数。