java - 将字符串输入二维数组
问题描述
尝试制作直方图,但我尝试使用的循环给了我一个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 数组中的每一行执行此操作。
解决方案
我认为问题可能出在 for 循环定义中,
for (int x = max; x > 0; x--)
您可以尝试将其更改为
for (int x = max-1; x >= 0; x--)
原因是,由于您定义了一个大小数组,max
并且索引从零开始max
实际上是在数组之外
推荐阅读
- asp.net-mvc-5 - Visual Studio 2017 无法启动调试适配器“chrome”
- r - 如何组合两个data.tables的列?
- load-testing - 如何为炮兵负载测试设置代理 url?
- python - Python 控制台菜单在 selection_menu 中运行 command_item
- javascript - 从 HTML 页面获取所有输入 id 值
- android-recyclerview - 创建2 RecyclerView 垂直滚动成水平滚动?
- wordpress - 如何使用 WAVE 可访问性报告解决此标签问题?
- amazon-redshift - 如果存在则删除组
- reactjs - SyntaxError:意外的令牌'...'。需要一个属性名称
- javascript - 比较和设置选择下拉值