gpt4 book ai didi

java - 如何按照说明显示两个数组

转载 作者:行者123 更新时间:2023-11-30 05:38:25 25 4
gpt4 key购买 nike

我正在为我的 Java 类(class)做这个作业,所以说明是:

"Write a program that generates 100 random integers in the range 1 to 100, and stores them in an array. Then, the program should call a class method that extracts the numbers that are even multiplesof4intoanarray and returns the array. The program should then call another method that extracts the numbers that are not even multiples of 4 into a separate array and returns the array. Both arrays should then be displayed."

public class Assignment8
{
public static void main (String [] args)
{
int [] numbers = new int [100];
for (int i = 1; i < numbers.length; i++) {
numbers[i] = (int)(Math.random()*((100)+1))+1;
}
int EMO4N [] = evenMultiplesOf4(numbers);
System.out.println("The even multiples of four are: ");
for (int m = 8; m < EMO4N.length; m++) {
System.out.println(EMO4N [m] + " " );
}
int NEMO4N [] = nonEvenMultiplesOf4(numbers);
System.out.println("The numbers that are not even multiples of four are: ");
for (int k = 1; k < NEMO4N.length; k++) {
System.out.println(NEMO4N [k] + " ");
}
}
public static int [] evenMultiplesOf4(int [] numbers)
{
int EMO4 = 8;
for (int x : numbers) {
if (x % 4 == 0 & (x / 4) % 2 == 0) {
EMO4++;
}
}
int [] EMO4N = new int [EMO4];
int y = 8;
for (int m : numbers) {
if(y % 4 == 0 & (y / 4) % 2 == 0) {
EMO4N[y] = m;
y++;
}
}
return EMO4N;
}

public static int [] nonEvenMultiplesOf4( int [] numbers)
{
int NEMO4 = 1;
for (int j : numbers) {
if (j % 4 != 0 || (j / 4) % 2 != 0) {
NEMO4++;
}
}
int [] NEMO4N = new int [NEMO4];
int k = 1;
for (int n : numbers) {
if(k % 4 != 0 || (k / 4) % 2 != 0) {
NEMO4N[k] = n;
k++;
}
}
return NEMO4N;
}
}

显示的结果始终是 0 和其他一些随机数的组合。

最佳答案

您有几个小逻辑错误。

  1. 您从 8 开始 my,这没有意义,因为它们旨在跟踪您要插入的索引。

  2. 您可以使用表达式 if (x % 4 == 0 & (x/4) % 2 == 0) 来确定该数字是否能被 4 整除,但是 if(x % 4 == 0) 就足够了。

  3. 在循环中:

for (int n : numbers) {
if(k % 4 != 0) {
NEMO4N[k] = n;
k++;
}
}

您正在检查k是否能被四整除,而您应该检查n。将其更改为:

for (int n : numbers) {
if(n % 4 != 0) {
NEMO4N[k] = n;
k++;
}
}

我不会提供工作代码,因为这似乎是一项家庭作业。

关于java - 如何按照说明显示两个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56177103/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com