gpt4 book ai didi

java - 我需要有关 Java 作业介绍的帮助

转载 作者:行者123 更新时间:2023-11-29 04:45:07 25 4
gpt4 key购买 nike

我已经成功编译了这个java程序(生成100个0到25之间的随机数,将它们放在一个数组中,并根据每个数组的奇偶性将它们排序到两个不同的数组中),虽然它没有运行。我怀疑我在其中一个 while 循环中犯了一个错误,尽管我不确定。此外,我努力让问题中的代码格式正确,因此选项卡有些偏离,但它仍然大部分清晰可见。这是 .java 文本:

public class Assignment8
{
public static void main( String [] args )
{
int storage [] = new int[100];
int j = 0;

while ( storage.length < 100 ) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
j++;
}

int oddArray[] = OddNumbers( storage );
int evenArray[] = EvenNumbers( storage );
int currentNumber = 0;

System.out.println( "The odd numbers are: " + "\n" );

while ( currentNumber <= 99 ) {
System.out.println( oddArray[currentNumber] + "\n" );
currentNumber++;
}

System.out.println( "\n" + "The even numbers are: " + "\n" );
currentNumber = 0;

while ( currentNumber <= 99 ) {
System.out.println( evenArray[currentNumber] + "\n" );
currentNumber++;
}
}

public static int[] OddNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int oddArray[] = new int[100];

while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 != 0 ) {
oddArray[currentNumber] = currentValue;
} else {
continue;
}

currentNumber++;
}

return oddArray;
}

public static int[] EvenNumbers( int storage[] )
{
int currentNumber = 0;
int currentValue = storage[currentNumber];
int evenArray[] = new int[100];

while ( currentNumber <= 99 ) {
if ( storage[currentNumber] % 2 == 0 ) {
evenArray[currentNumber] = currentValue;
} else {
continue;
}

currentNumber++;
}

return evenArray;
}
}

最佳答案

storage.length 在整个程序执行期间不会改变,因为数组已经分配。因此,您的第一个 while 循环是错误的,因为 100 不小于 100,它永远不会执行。相反,您可以使用简单的 for 循环:

for (int j  = 0; j < storage.length; ++j) {
int testVariable = 0 + (int) (Math.random() * ((25 - 0) + 1));
storage[j] = testVariable;
}

关于java - 我需要有关 Java 作业介绍的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37503881/

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