下面写的代码是正确的,但我想缩短这段代码。
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]);
}
我可以在单个 for 循环而不是两个 for 循环中安排偶数和奇数吗?我正在使用两个 for 循环将偶数和奇数传输到 b[]
数组中。请缩短代码。一个 for 循环遍历用于检查偶数,第二个用于检查奇数。
最佳答案
这是一个简单的程序。
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);
}
}
关于java - 显示偶数后跟所有奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55236124/