Java 如何按顺序打印奇数和偶数

Java 如何按顺序打印奇数和偶数,java,arrays,data-structures,Java,Arrays,Data Structures,下面的代码是在删除偶数后得到的输出,但这里的情况是 如果任何框包含奇数,则必须使用偶数打印整个框号,即使奇数之间有偶数 条件:如果第一个框包含奇数,则不能接受该框并打印“对不起” 请检查代码,我需要的输出在预期输出块中给出 import java.util.*; class Chocolate { public static void main(String[] args) { Scanner sc = new Scanner(System.in); S

下面的代码是在删除偶数后得到的输出,但这里的情况是

如果任何框包含奇数,则必须使用偶数打印整个框号,即使奇数之间有偶数

条件:如果第一个框包含奇数,则不能接受该框并打印“对不起” 请检查代码,我需要的输出在预期输出块中给出

import java.util.*;

class Chocolate {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter the no. of boxes:");
        int no = sc.nextInt();
        if (no <= 0 || no > 10) {
            System.out.println("Invalid input");
        } else {
            int[] ch = new int[no];
            for (int i = 0; i < no; i++) {
                System.out.print("\nEnter the no. of chocolates in box " + (i + 1) + ":");
                ch[i] = sc.nextInt();
            }
            System.out.print("\nNo of chocolates in each box:");
            for (int i = 0; i < ch.length; i++) {
                if (ch[i] % 2 != 0) {
                    System.out.print(ch[i] + " ");
                }
            }
        }
    }
}
期望

Enter the no. of boxes: 5

Enter the no. of chocolates in box 1: 4

Enter the no. of chocolates in box 2: 2

Enter the no. of chocolates in box 3: 3

Enter the no. of chocolates in box 4: 6

Enter the no. of chocolates in box 5: 1

No. of chocolates in each box: 3 6 1

你可以试试类似的东西

String s = "";
boolean x = false;
int odd = 0;
for(int i=0;i<a.length;i++) //a is your array
    if(a[i]%2!=0)odd++;
for(int i=0;i<a.length && odd>0;i++){
    if(a[i]%2!=0){
        x = true;
        s+=a[i] + " ";
        odd--;
    }else{
        if(x) s+=a[i] + " ";
    }
}
System.out.println(s);
String s=”“;
布尔x=假;
int奇数=0;

对于(int i=0;我不完全理解您的作业,但从预期输出来看,我认为您需要“展望未来”在你的最后一个循环中,这样你也可以检查下一步是什么。你必须包括两个奇数之间有多个偶数的可能性吗?或者它总是一个数字吗?它可能会像425221一样,不会给我带来完整的数字,例如我拿了23145,那么输出应该是3145,我只得到314
String s = "";
boolean x = false;
int odd = 0;
for(int i=0;i<a.length;i++) //a is your array
    if(a[i]%2!=0)odd++;
for(int i=0;i<a.length && odd>0;i++){
    if(a[i]%2!=0){
        x = true;
        s+=a[i] + " ";
        odd--;
    }else{
        if(x) s+=a[i] + " ";
    }
}
System.out.println(s);