【问题标题】:How to print the first character in a two dimensional array如何打印二维数组中的第一个字符
【发布时间】:2020-02-25 01:56:33
【问题描述】:

我正在尝试将每个单词的第一个字符打印到二维数组中。当我尝试使用子字符串打印它时出现错误。

String [][] manyWords = { 
        {"red", "bling", "grand"},
        {"bridge", "queen", "chair"}
    };
    System.out.print(manyWords.substring(0, 1));

我收到一个无法编译的源代码错误。

【问题讨论】:

  • manywords 是任意数组...... substring() 是 String 类上的一个方法......
  • 您必须遍历数组中的元素。包含对象的数组就是对象。数组本身没有数组中的元素所拥有的方法。

标签: java


【解决方案1】:

以下代码应该可以实现您的目标:

    public class test{

      public static void main(String[] args){

    // Declare test array
    String [][] manyWords = { 
            {"red", "bling", "grand"},
            {"bridge", "queen", "chair"}
        };

    // Since it is a 2d array, loop through it with both an x and y coordinate
    // Check https://stackoverflow.com/questions/25798958/iterate-through-2-dimensional-array for more info
    for (int i = 0; i < manyWords.length; i++){
      for (int j = 0; j < manyWords[i].length; j++){

        // Set the current character using charAt
        char curr = manyWords[i][j].charAt(0);

        // Print it out
        System.out.println(curr);

      } //end inner for
    } //end outer for
  } //end psvm
} //end class

打印:

r
b
g
b
q
c

【讨论】:

    【解决方案2】:

    你必须使用一些循环(我更喜欢 for-each 而不是 for/while):

    for(String[] strArr : manyWords){
       for(String str : strArr){
           System.out.println(str.substring(0,1);}}
    

    【讨论】:

      【解决方案3】:

      这是一个流版本:

      Stream.of(manyWords).flatMap(Stream::of).map(s -> s.substring(0, 1))
          .forEach(System.out::print);
      

      【讨论】:

        【解决方案4】:

        你可以这样做。希望对您有所帮助。

        String [][] manyWords = { {"red", "bling", "grand"}, {"bridge", "queen", "chair"} };
        
        for (int i = 0; i < manyWords.length; i++) {
           for (int j = 0; j < manyWords[i].length; j++) {
                  System.out.print(manyWords[i][j].substring(0, 1) + " ");
           }
        }
        

        【讨论】:

          猜你喜欢
          • 2019-10-24
          • 2023-03-13
          • 1970-01-01
          • 2022-11-16
          • 1970-01-01
          • 2018-09-29
          • 1970-01-01
          • 1970-01-01
          • 2012-03-15
          相关资源
          最近更新 更多