以下代码需要按顺序和反向顺序打印数组中的随机数。我有相反的订单打印但由于某种原因我似乎无法按原始顺序打印。我不知道要修改什么。我目前所印刷的是“按顺序”的空白行和“反向订单”的数字。我需要修理什么?谢谢!
public class RandomPrintOut
{
//-----------------------------------------------------------------
//
//-----------------------------------------------------------------
public static void main (String[] args)
{
int numbers[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
numbers [i] = (int) (Math.random () * 100);
}
System.out.println ("The size of the array: " + numbers.length);
System.out.println ("The numbers in order:");
for (int index = numbers.length+1; index <= 10; index++)
System.out.print (numbers[index] + " ");
System.out.println ("\nThe numbers in reverse order:");
for (int index = numbers.length-1; index >= 0; index--)
System.out.print (numbers[index] + " ");
}
}
答案 0 :(得分:3)
对于以下代码:
for (int index = numbers.length+1; index <= 10; index++)
此处index
的初始值为 number.length + 1 ,此值为 10+1=11
。 这大于10,因此,在这个for循环中永远不会满足该编码。这就是阵列没有按顺序打印的原因。
您需要按如下方式进行更改:
弗罗姆
for (int index = numbers.length+1; index <= 10; index++)
System.out.print (numbers[index] + " ");
到
for (int index = 0; index <10; index++)
System.out.print(numbers[index] + " ");
更改后的代码如下:
公共类RandomPrintOut { // ------------------------------------------------ ----------------- // // ------------------------------------------------ ----------------- public static void main(String [] args) {
int numbers[] = new int [10];
for (int i = 0 ; i < 10 ; i++)
{
numbers [i] = (int) (Math.random () * 100);
}
System.out.println ("The size of the array: " + numbers.length);
System.out.println ("The numbers in order:");
for (int index = 0; index < 10; index++)
System.out.print (numbers[index] + " ");
System.out.println ("\nThe numbers in reverse order:");
for (int index = numbers.length-1; index >= 0; index--)
System.out.print (numbers[index] + " ");
} }
在控制台中打印的结果输出:
The size of the array: 10
The numbers in order:
31 50 49 99 29 54 41 16 7 21
The numbers in reverse order:
21 7 16 41 54 29 99 49 50 31
答案 1 :(得分:0)
仔细查看此循环中index
的值
for (int index = numbers.length+1; index <= 10; index++)
System.out.print (numbers[index] + " ");
尝试手动完成并查看它的外观。这应该可以帮助您确定问题。
答案 2 :(得分:0)
public class RandomPrintOut {
//-----------------------------------------------------------------
//
//-----------------------------------------------------------------
public static void main (String[] args) {
int numbers[] = new int [10];
for (int i = 0 ; i < 10 ; i++) {
numbers [i] = (int) (Math.random () * 100);
}
System.out.println ("The size of the array: " + numbers.length);
System.out.println ("The numbers in order:");
for (int index = 0; index <= numbers.length-1; index++) {
System.out.print (numbers[index] + " ");
}
System.out.println ("\nThe numbers in reverse order:");
for (int index = numbers.length-1; index >= 0; index--) {
System.out.print (numbers[index] + " ");
}
}
}