简体   繁体   English

显示偶数后跟所有奇数

[英]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.用java编写一个程序,在一维数组中输入10个数字,并将它们排列成所有偶数后跟所有奇数。

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?我可以在一个 for 循环而不是两个 for 循环中排列偶数和奇数吗? I am using two for loop to transfer the even and the odd numbers into b[] array.我使用两个 for 循环将偶数和奇数传输到b[]数组中。 Please shorten code.请缩短代码。 One for loop traverse for checking even number and second for odd numbers.一个 for 循环遍历检查偶数,第二个检查奇数。

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:我创建了一个简单的示例,其中在将 String 解析为 int 时没有检查NumberFormatException

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 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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