我在 for 循环中使用数组时遇到了困难,该数组应该按降序排列数字 1-9 的立方。我不断收到越界错误,并且立方值完全关闭。我非常感谢您能解释一下我在考虑数组时出错的地方。我相信问题出在我的索引上,但我很难解释原因。
System.out.println("***** Step 1: Using a for loop, an array, and the Math Class to get the cubes from 9-1 *****");
System.out.println();
// Create array
int[] values = new int[11];
int[] moreValues = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Create variable to store cubed numbers
double cubedNumber = 0;
// Create for loop to count in descending order
for (int counter = 9; counter < moreValues.length; counter--)
{
cubedNumber = Math.pow(counter,3);
System.out.println(moreValues[counter] + " cubed is " + cubedNumber);
}
最佳答案
你的主要错误是循环终止条件 counter < moreValues.length
,如果您倒数,则该结果永远为真。
相反,检查索引是否等于或大于零:
for (int counter = 9; counter >= 0; counter--)
您的另一个错误是您正在计算索引的立方,而不是索引指向的数字,因此请改为编码;
cubedNumber = Math.pow(moreValues[counter], 3);
为了减少困惑,您最好为循环变量使用行业标准名称,例如 i
或者当循环变量被用作数组的索引时,index
经常使用,可以提高代码清晰度。
关于java - 数组中的 For 循环 (Java) 索引越界,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47358711/