我是Java的新手并且坚持以下任务 . 我们正在使用数组,并且应该根据我们的输入创建一个长度为数组的数组 . 除了 main()
之外,不允许使用其他方法 .
然后输入数组将随机选择0-999之间的整数并将它们放入数组中,然后我们应该创建一个具有相同数字和长度的新数组,但首先使用偶数进行排序,然后使用奇数进行排序 .
例:
How many variables do you want? 4
Here are the random variables: 4 7 8 1
Here are the sorted variables: 4 8 7 1
Of your chosen variables 2 are even and 2 are odd
到目前为止我的代码是这样的 .
public static void main(String[] args)
{
int checker;
int even = 0;
int odd = 0;
Scanner s = new Scanner(System.in);
System.out.print("How many variables between 0-999 you want?: ");
int n = s.nextInt();
int arr[] = new int[n];
int ord[] = new int[n];
for(int i = 0; i < n; i++)
{
arr[i] = (int) (Math.random() * 100) + 1;
}
System.out.print("Here are your random numbers: ");
for(int i : arr)
{
System.out.print(i + " ");
}
for(int i = 0; i < n - 1; i++)
{
checker = arr[i] % 2;
if(checker == 0)
{
even = even + 1;
}
else
{
odd = odd + 1;
}
}
System.out.print("Of the chosen numbers" + even + "is even and" + odd + "is odd");
}
4 回答
首先,
arr[i]=(int)(Math.random()*100)+1;
是错误的 . 这将为您提供1-100的数字,而不是0-999 . 你需要像这样写:arr[i]=(int)(Math.random()*1000);
其次,你的最后一个for循环的条件是
i<n-1
而不是i<n
. 这也需要修复 .现在,我们只需要对数组进行排序 . 我们已经遍历数组来计算偶数和奇数的数量,所以我们不妨同时对数组进行排序 .
让我们有两个额外的空数组,一个用于偶数,一个用于奇数,我们暂时存储值:
现在,每次我们找到偶数或奇数时,我们都可以将它们插入其中一个数组中:
现在,我们所要做的就是将这两个数组中的值插入到最终数组_2475297中:
现在我们有了排序数组,正如我们想要的那样 .
现在您可以按照打印未排序数组的方式打印它:
我看到有些人打败了我,但无论如何我都会回答并给你一些建议 .
这是您应该在最后一个for循环后面添加的代码 .
它的作用是将偶数放在数组的开头,偶数放在数组的末尾 .
你还应该修复你的for循环:'for(int i = 0; i <n - 1; i)' . 在这种情况下,它将运行一次比你想要的少 . 要么放'i <= n-1'或'i < n',要么最好的选择是使用'i < array.length',每当你更改阵列时它都会改变,你不必担心每次都改变它 .
现在提供建议......编写如下代码:
可以像这样改进:
它看起来更好 .
使编程更容易的另一件事是使用i(或i--)将变量增加1.它节省了一点点打字 . 或者如果你想增加更多,你可以使用i = 3或i- = 7 .
希望这可以帮助
最好的解决方案是编写自己的比较器:首先比较一个是偶数,另一个是奇数 . 如果他们是你已经知道哪一个应该先走,否则自然比较 .
您可以通过修改最终循环来轻松完成此操作 . 关键是从正面填充偶数的数组,从背面填充奇数 . 当你完成后,
even
索引会告诉你有多少偶数 . 像这样: