如何在列表中找到每个单词的字符数? (Java)的

时间:2017-02-23 06:29:46

标签: java string list

我希望输出说出

每个单词的总字母数为:

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

       }
}
  

块引用

2 个答案:

答案 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!