如何使用迭代打印所有内容,在同一行上打印数组中的特定字符串和双精度数组中的数组值?

问题描述 投票:0回答:1

我基本上必须创建一个方法,该方法接受一个字符串数组和一个由三个双精度数组组成的二维数组,并将第一个字符串与第一个数组一起放置,第二个字符串与第二个数组一起放置,依此类推。

public static void printData(String[] c, double[][] d)
{
        String cname = "";
        for(int i = 0; i < c.length; ++i)
    {
        cname = c[i];
           for(int row = 0; row < d.length; ++row)
       {
              for(int col = 0; col < d[0].length; ++col)
              {
                  System.out.print(d[row][col] + " ");
              } 
              System.out.println();
       }

    }

多次打印数组

//String word = "";

    //for(int i = 0; i < c.length; ++i)
  //{
        //for(int row = 0; row < d.length; ++row)
    //{ 
        //System.out.println();
        //for(int col = 0; col < d[0].length; ++col)
        //{
            //word = c[i];
            //System.out.println(d[i][col]);
        //}
    
    //}
  //}

我确实能够打印出城市名称,并在其下方显示整个二维数组。

java multidimensional-array
1个回答
-1
投票

要实现在同一行上打印 c 数组中的每个字符串及其 d 二维数组中相应的双精度数组,您应该同时迭代这两个数组。以下是修改方法的方法:

public static void printData(String[] c, double[][] d) {
for (int i = 0; i < c.length; ++i) {
    // Print the string from the c array
    System.out.print(c[i] + " ");

    // Print the corresponding double array from the d 2D array
    for (int col = 0; col < d[i].length; ++col) {
        System.out.print(d[i][col] + " ");
    }

    // Move to the next line for the next string and its corresponding double array
    System.out.println();
}

此修改后的方法将在同一行上打印 c 数组中的每个字符串以及 d 二维数组中相应双精度数组的值。

© www.soinside.com 2019 - 2024. All rights reserved.