在数组中存储的数字在Java中出现错误。

huangapple 未分类评论45阅读模式
英文:

error in the number stored in the array java

问题

以下是翻译好的内容:

在我编写代码时,我需要打印出总共25个数字,所以我将数字25放入了numberArray中,然而当我运行程序时,它没有打印出25个数字。相反,随机数字的数量不断变化,并且没有固定在特定的值上。在这种情况下,我该怎么做才能让我的代码打印出25个数字?

public static void printArray(int[] ear) {
    
    System.out.println("奇数:");
    for (int e = 0; e < ear.length; e++) {
        ear[e] = (int) (Math.random() * 100);
        if (ear[e] % 2 != 0)
            System.out.print(ear[e] + "  ");
    }
    System.out.println("\n" + "偶数:");
    for (int e = 0; e < ear.length; e++) {
        ear[e] = (int) (Math.random() * 100);
        if (ear[e] % 2 == 0)
            System.out.print(ear[e] + "  ");
    }
    
}

public static void main(String[] args) {
    int[] numberArray = new int[25];
    printArray(numberArray);
}
英文:

While I was writing the code, I had to print out total 25 numbers, so I put the number 25 inside the numberArray, however when I run the program, it dd not print out 25 numbers. Instead the number of the random numbers kept changing and did not stick to the specific value. What should I do in this case to make my code print out 25 numbers?

public static void printArray(int[] ear) {
	
	System.out.println(&quot;ODD NUMBERS : &quot;);
	for (int e = 0; e&lt;ear.length ; e ++) {
		ear[e] = (int)(Math.random()* 100);
			if(ear[e]%2!=0)
			System.out.print(ear[e] + &quot;  &quot;);
	}
	System.out.println(&quot;\n&quot; + &quot;EVEN NUMBERS : &quot;);
	for (int e = 0; e&lt;ear.length ; e ++) {
		ear[e] = (int)(Math.random()* 100);
			if(ear[e]%2==0)
			System.out.print(ear[e] + &quot;  &quot;);
	}
	
}

public static void main(String[] args) {
	int[] numberArray = new int[25];
	printArray(numberArray);

}

}

答案1

得分: 0

根据代码中的说明,您只打印了数组的奇数和偶数。这就是为什么每次运行时会得到不同的结果。

如果您将代码更改为打印数组索引而不是值,您会看到您正在打印

奇数:
4  10  12  13  14  15  18  19  22  23  24
偶数:
0  1  3  4  5  6  9  13  16  17  18  19  20  22  23
英文:

As stated in the code, you are only printing the ODD and EVEN numbers of the array. That's why you get different outcomes on each run.

If you change the code to print the array index instead of the value you can see that you are printing

ODD NUMBERS : 
4  10  12  13  14  15  18  19  22  23  24  
EVEN NUMBERS : 
0  1  3  4  5  6  9  13  16  17  18  19  20  22  23 

huangapple
  • 本文由 发表于 2020年7月23日 10:03:45
  • 转载请务必保留本文链接:https://java.coder-hub.com/63045757.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定