对于我的Java类,我有这个任务:
编写一个程序,生成0到25范围内的100个随机整数,并将它们存储在一个数组中。然后,程序应该调用一个类方法,将奇数排序成一个数组并返回该数组。然后程序应该调用另一个方法,将偶数分类到一个单独的数组中并返回数组。然后应显示两个数组。
这是我的代码:
public class XandY
{
public static void main(String [] args)
{
int [] randomNums = new int [100];
for (int i = 0; i < randomNums.length; i++) {
randomNums[i] = (int) (Math.random() * 26);
int[] oddNums = sortOdd(randomNums);
System.out.println("The odd numbers are ");
for (int n = 0; n<=oddNums.length; n++) {
System.out.print(n);
}
int[] evenNums = sortEven(randomNums);
System.out.println("The even numbers are ");
for (int o = 0; o<=evenNums.length; o++) {
System.out.print(o);
}
}
}
public static int[] sortOdd(int[] randomNums)
{
int numOdds = 0;
for (int x : randomNums){
if(x % 2 == 1){
++numOdds;
}
}
int[] oddNums = new int[numOdds];
int z = 0;
for (int n : randomNums){
if(n % 2 == 1){
oddNums[z] = n;
z++;
}
}
return oddNums;
}
public static int[] sortEven(int[] randomNums)
{
int numEvens = 0;
for (int x : randomNums){
if(x % 2 == 0){
++numEvens;
}
}
int[] evenNums = new int[numEvens];
int z = 0;
for (int n : randomNums){
if(n % 2 == 0){
evenNums[z] = n;
z++;
}
}
return evenNums;
}
}
运行时会显示一堆随机数。任何人都可以帮忙吗?提前谢谢。
答案 0 :(得分:1)
除了你的主要方法外,一切都很好。
public static void main(String [] args)
{
int [] randomNums = new int [100];
for (int i = 0; i < randomNums.length; i++) {
randomNums[i] = (int) (Math.random() * 26);
}
int[] oddNums = sortOdd(randomNums);
System.out.println("The odd numbers are ");
for (int n = 0; n<oddNums.length; n++) {
System.out.print(oddNums[n] + " " );
}
int[] evenNums = sortEven(randomNums);
System.out.println("The even numbers are ");
for (int o = 0; o<evenNums.length; o++) {
System.out.print(evenNums[o] + " ");
}
}