我需要编写一个java程序,将整数数组中的偶数和奇数分开。
这是我到目前为止所做的: 这部分是完美的:
package Homework;
import java.util.*;
public class EvenOdd
{
public static void main(String[] args)
{
// TODO Auto-generated method stub
System.out.println("Please enter 10 integers");
int [] a= new int[10];
Scanner sc = new Scanner(System.in);
for(int i=0;i<a.length;i++)
{
System.out.print("The "+(i+1)+" integer = ");
a[i]= sc.nextInt();
}
System.out.println("\nThe resulting array");
for(int i=0;i<a.length;i++)
{
for(int j=1;j<a.length;j++)
{
int temp;
if(a[i]%2!=0 && a[j]%2==0 && j>i)
{
temp=a[j];
a[j]=a[i];
a[j]=temp;
break; //There seems to be some problem in this loop
}
}
System.out.println("The "+(i+1)+" integer = "+a[i]);
}
答案 0 :(得分:1)
如果你使用模数%2
,你应该能够找到数字是偶数还是奇数,因为偶数数字mod 2将等于0而奇数数字mod 2将等于1。
尝试使用此方法对数组进行排序:
for(int i=0;i<count;i++)
{
if(a[i] %2 != 0){//even
int temp = a[i];
a[i--] = a[count--];
a[count+1] = temp;
}
}
答案 1 :(得分:1)
介绍两个Integer类型的ArrayLists list1和list2。将偶数和list1和奇数放入list2。将两者合并到list1中。
<?=fuel_nav()?>
答案 2 :(得分:1)
import java.util.*;
class main11
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter the range");
int no=sc.nextInt();
int a[]=new int[no];
int i;
System.out.println("Enter the elements");
for(i=0;i<no;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Even nos are");
for(i=0;i<no;i++)
{
if(a[i]%2==0)
{
System.out.println(a[i]);
}
}
System.out.println("The odd nos are");
for(i=0;i<no;i++)
{
if(a[i]%2!=0)
{
System.out.println(a[i]);
}
}
}
}
答案 3 :(得分:0)
我认为由于拼写错误,你的元素交换无效:
temp=a[j];
a[j]=a[i];
a[i]=temp; //Should be a[i] and not a[j]
break;
您还可以通过在for
循环中进行以下更改来减少迭代次数:
for(int i=0;i<a.length-1;i++)
{
for(int j=i+1;j<a.length;j++)
{
int temp;
if(a[i]%2!=0 && a[j]%2==0) //no need of the last condition
答案 4 :(得分:0)
set_richcompare()
答案 5 :(得分:0)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
int j=0,k=0,n;
Scanner scn = new Scanner(System.in);
System.out.println("Enter number of element you want in your array:");
n = scn.nextInt();
int array[] = new int[n];
System.out.println("Your array element is : ");
for (int i=0;i<n;i++){
array[i]= scn.nextInt();
}
int even[] = new int[n];
int odd[] = new int[n];
for (int i=0;i<n;i++){
if (array[i] % 2 != 0){
odd[j] = array[i];
j++;
}
else{
even[k] = array[i];
k++;
}
}
System.out.println("Odd Array");
if (j>1)
{
for (int i=0;i<j-1;i++){
System.out.println(odd[i]+",");
}
System.out.println(odd[j-1]);
}
else {
System.out.println("No number");
}
System.out.println(" ");
System.out.print("Even :");
System.out.println("Odd Array");
if (k>1)
{
for (int i=0;i<k-1;i++){
System.out.println(even[i]+",");
}
System.out.println(even[k-1]);
}
else {
System.out.println("No number");
}
}
}