简体   繁体   中英

to display the even number followed by all odd numbers

Code written below is correct, but I want to shorten this code.

Write a program in java to enter 10 numbers in Single dimensional array and arrange them in such a way that all even numbers are followed by all odd numbers.

int a[] = new int[6];
int b[] = new int[6];
int i, j;
int k = 0;
System.out.println("enter array");
for (i = 0; i < 6; i++) {  
    a[i] = sc.nextInt();
}
for (j = 0; j < 6; j++) {
    if (a[j] % 2 == 0) {
        b[k] = a[j];
        k++;
    }
}
for (j = 0; j < 6; j++) {
    if (a[j] % 2 != 0) {
        b[k] = a[j];
        k++;
    }
}
System.out.println("out-put");
for (i = 0; i < 6; i++) {  
    System.out.println(b[i]);
}

Can I arrange the even numbers and the odd numbers in a single for loop instead of two for loop? I am using two for loop to transfer the even and the odd numbers into b[] array. Please shorten code. One for loop traverse for checking even number and second for odd numbers.

Here is a simple program for you.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;

/**
 *
 * @author Momir Sarac
 */
public class GroupByEvenAndOddNumbers {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // create a collection
        List<Integer> listOfNumbers = new ArrayList<>();
        // do code within a loop for 10 times
        for(int i=0;i<10;i++)
        {
            //print to screen this text
            System.out.println("Input your number:");
            //get next input integer
            int number = scanner.nextInt();
            // add it to collection
            listOfNumbers.add(number);
        }
        // sort this collection, list of numbers
        // convert all numbers(positive and negative ) within to 0 or 1 depending whether or not they are even or odd and sort them accordignaly.
        Collections.sort(listOfNumbers, Comparator.comparingInt(n -> Math.floorMod(n, 2)));
        //print sorted collection
        System.out.println("Ordered list ..." + listOfNumbers);
    }
}

In this version, it copies the even to the start, and the odd to the end.

static int[] sortEvenOdd(int... nums) {
    int even = 0, odd = nums.length, ret[] = new int[nums.length];
    for (int num : nums)
        if (num % 2 == 0)
            ret[even++] = num;
        else
            ret[--odd] = num;
    return ret;
}

public static void main(String[] args) {
    int[] arr = {1, 3, 2, 4, 7, 6, 9, 10};
    int[] sorted = sortEvenOdd(arr);
    System.out.println(Arrays.toString(sorted));
}

prints

[2, 4, 6, 10, 9, 7, 3, 1]

This Code will help you to segregate Even and Odd numbers.

// java code to segregate even odd 
// numbers in an array 
public class GFG { 

// Function to segregate even 
// odd numbers 
static void arrayEvenAndOdd( 
            int arr[], int n) 
{ 

    int i = -1, j = 0; 
    while (j != n) { 
        if (arr[j] % 2 == 0) 
        { 
            i++; 

            // Swapping even and 
            // odd numbers 
            int temp = arr[i]; 
            arr[i] = arr[j]; 
            arr[j] = temp; 
        } 
        j++; 
    } 

    // Printing segregated array 
    for (int k = 0; k < n; k++) 
        System.out.print(arr[k] + " "); 
} 

// Driver code 
public static void main(String args[]) 
{ 
    int arr[] = { 1, 3, 2, 4, 7, 
                        6, 9, 10 }; 
    int n = arr.length; 
    arrayEvenAndOdd(arr, n); 
 } 
} 

As you don't have any requirements that the even and odd numbers itself have to be ordered in their respectively half of the array you can just assign them to their associated array part while entering them. Therefore you just have to use two "counter" variables one for the left which starts at zero and is incremented and one for the right which starts at your array length minus one and is decremented. Then you can add your numbers, checking if one is even add assign it with your left counter post incremented and if one is odd assign it with your right counter post decremented. Do this within a loop, until your left counter is bigger than your right counter. I created a simple example where I did not check for NumberFormatException when parsing the String to an int:

import java.util.Arrays;
import java.util.Scanner;

public class SortedArrayInput {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        System.out.print("Enter length of array: ");
        final int arrayLength = Integer.parseInt(scanner.nextLine());

        int intArray[] = new int[arrayLength];
        for (int l = 0, r = arrayLength - 1; l <= r; ) {
            System.out.print("Enter new array value: ");
            int v = Integer.parseInt(scanner.nextLine());
            intArray[v % 2 == 0 ? l++ : r--] = v;
        }

        System.out.println("Output: " + Arrays.toString(intArray));
    }
}

Sample input/output:

Enter length of array: 6
Enter new array value: 1
Enter new array value: 2
Enter new array value: 3
Enter new array value: 4
Enter new array value: 5
Enter new array value: 6
Output: [2, 4, 6, 5, 3, 1]

I recommend reading up on streams, they will make collection processing a lot easier for you

List<Integer> numbers = new ArrayList<>();
        numbers.add(1);
        numbers.add(2);
        numbers.add(3);
        numbers.add(4);
        numbers.add(5);
        numbers.add(6);
        numbers.add(7);
        numbers.add(8);
        numbers.add(9);
        numbers.add(0);

        //this way you simply traverse the numbers twice and output the needed ones
        System.out.println(numbers.stream()
                .filter(x->x%2==0)
                .collect(Collectors.toList()));
        System.out.println(numbers.stream()
                .filter(x->x%2==1)
                .collect(Collectors.toList()));

        //this way you can have the numbers in two collections
        numbers.forEach(x-> x%2==0? addItToEvenCollection : addItToOddCollection);

        //this way you will have a map at the end. The boolean will tell you if the numbers are odd or even, 
        // and the list contains the numbers, in order of apparition in the initial list
        numbers.stream().collect(Collectors.groupingBy(x->x%2==0));

检查数字是否为偶数的一种高效方法是使用 if ( (x & 1) == 0 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM