我希望输出说出
每个单词的总字母数为:
Emma = 4
泰勒= 6
雅各布= 5
罗杰= 5
JP = 2
我知道我的for循环错误,它会输出所有名称的总字符数。
先谢谢。
块引用
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
}
}
块引用
答案 0 :(得分:2)
你做的事情太复杂了,而不是尝试这样的事情:
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());
}
}
答案 1 :(得分:0)
为什么不迭代myList
并打印出每个单词的长度(字符数量),如下所示:
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args) {
List<String> myList = Arrays.asList("Emma", "Taylor", "Jacob", "Roger", "JP");
System.out.println(Arrays.toString(myList.toArray()));
System.out.println("Total letters per word is: ");
for(String name : myList) {
System.out.printf("%s = %d\n", name, name.length());
}
}
}
<强>输出:强>
[Emma, Taylor, Jacob, Roger, JP]
Total letters per word is:
Emma = 4
Taylor = 6
Jacob = 5
Roger = 5
JP = 2
测试here!