首页 > 解决方案 > 将字符串输入二维数组

问题描述

尝试制作直方图,但我尝试使用的循环给了我一个Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 14错误。我试图得到一些类似的东西:

*       *               
*       *       *       *       
*       *   *   *       *   *   
*       *   *   *       *   *   
*       *   *   *   *   *   *   
*       *   *   *   *   *   *   *   *
*   *   *   *   *   *   *   *   *   *
*   *   *   *   *   *   *   *   *   *
*   *   *   *   *   *   *   *   *   *
*   *   *   *   *   *   *   *   *   *
*   *   *   *   *   *   *   *   *   *
*   *   *   *   *   *   *   *   *   *
*   *   *   *   *   *   *   *   *   *
-   -   -   -   -   -   -   -   -   -
0   1   2   3   4   5   6   7   8   9

这就是我到目前为止所拥有的:

public static void VerticalHist()
   {
      int max = 0; // initialize max

      int[] count = new int[10]; // make array to find max

      for (int i = 0; i < 100; i++)
      {
         int rand = (int)(Math.random() * ((9 - 0) + 1)); // generate random values

         count[rand]++;
      }

      for (int x : count) // find max 
      {
         if (x > max)
            max = x;
      }

      // System.out.println(max);
      String[][] nums2 = new String[max][10]; // create 2d array for histogram

      for (int x = max; x > 0; x--)
      {
         System.out.println();
         for (int i = 0; i < nums2[x].length; i++)
         {
            if (count[i] > 0)
               nums2[x][i] = "*";
         }
      }

      for (int i = 0; i < max; i++) // print 2d array
      {
         System.out.println();
         for (String n: nums2[i])
         {
            System.out.print(n);
         }
      }

   }

我插入 * 的循环给了我错误。

for (int x = max; x > 0; x--)
      {
         System.out.println();
         for (int i = 0; i < nums2[x].length; i++)
         {
            if (count[i] > 0)
               nums2[x][i] = "*";
               count[i]--;
            else
               nums2[x][i] = "";
         }
      }

我正在尝试获取每一行,检查每个索引以查看是否需要有一个星号,(如果是,则放一个星号,如果不放一个空格)并对 2d 数组中的每一行执行此操作。

标签: javaarrays

解决方案


我认为问题可能出在 for 循环定义中,

for (int x = max; x > 0; x--)

您可以尝试将其更改为

for (int x = max-1; x >= 0; x--)

原因是,由于您定义了一个大小数组,max并且索引从零开始max实际上是在数组之外


推荐阅读