gpt4 book ai didi

java - 如何查找列表中每个单词的字符数? ( java )

转载 作者:行者123 更新时间:2023-12-02 03:00:38 24 4
gpt4 key购买 nike

我想要输出说

每个单词的总字母数为:

艾玛=4

泰勒 = 6

雅各布 = 5

罗杰=5

日本 = 2

我知道我的 for 循环是错误的,它输出所有名称的总字符数。

Blockquote

public static void main(String[] args){

List<String> myList = Arrays.asList("Emma", "Taylor", "Jacob", "Roger", "JP");// list of names

String[] arrayOfNames = new String[myList.size()];

myList.toArray(arrayOfNames);


System.out.println("List of names: " +
Arrays.toString(arrayOfNames));

String myL = myList.toString();

String[] words = myL.split(" ");

int total = 0;

for (int i = 0; i < words.length; i++) //for loop incorrect

{

total += words[i].length();
}

System.out.println("Total letters per word is: "+total);//see above

}
}

Blockquote

最佳答案

你把事情搞得太复杂了,需要尝试这样的事情:

public static void main (String[] args) throws java.lang.Exception
{
List<String> myList = Arrays.asList("Emma", "Taylor", "Jacob", "Roger", "JP");
System.out.println("Total letters per word is: ");
for (int i = 0; i < myList.size(); i++) //for loop incorrect
{
System.out.println(myList.get(i)+" = " + myList.get(i).length());
}
}

关于java - 如何查找列表中每个单词的字符数? ( java ),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42408562/

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