如何终止此循环?

时间:2015-10-06 02:40:24

标签: java

“只应使用一个while循环来确定50到100之间的所有偶数和奇数。”

public class EvenOdd {

public static void main(String args[]) {

    int x = 50;
    int y = 50;
    int i = 0;
    int j = 0;
    int n = 0;

    System.out.print("Even numbers between 50 and 100: ");
    while((i != x) || (j != y)) {
        n++;
        System.out.print(i + x + ", ");
        i += 2;
        if(i != x)
            continue;

        System.out.println("100");

        System.out.print("\nOdd numbers between 50 and 100: ");

        System.out.print((j+1) + y + ", ");
        j += 2;

        if(j != y)
            continue;

    }       
  }
}

平均打印很好,但可能性永远存在。这可能是一个愚蠢的问题,但我现在正拥有最大的脑筋,我真的很感激这方面的帮助。

4 个答案:

答案 0 :(得分:0)

也许你应该试试这个

    int even_counter = 50;
    int odd_counter=51;
    System.out.println("Even numbers between 50 and 100: ");
    while((even_counter < 100 ) || (odd_counter < 100)){
        if(even_counter < 100){
            System.out.print(even_counter+ " ");
            even_counter+=2;
            continue;
        }

        if(odd_counter < 100){
            if(odd_counter == 51){
                System.out.println("\nOdd numbers between 50 and 100: ");
            }
            System.out.print(odd_counter+ " ");
            odd_counter+=2;
        }

    }

答案 1 :(得分:0)

只需尝试这个并告诉我。它基于您的代码,只需进行一些小的调整:

public class Teste4 {

public static void main(String args[]) {

    int x = 50;
    int y = 50;
    int i = 0;
    int j = 1;
    int n = 0;

    System.out.print("Even numbers between 50 and 100: ");
    while((i < x) || (j < y)) {
        if(i < x){
            System.out.print(i + x + ", ");
            i += 2;
            continue;
        }else if(i == x){
            System.out.println("100");
            i++;
        }

        if(j == 1){
            System.out.print("\nOdd numbers between 50 and 100: ");
        }

        System.out.print(j + y + ", ");
        j += 2;
    }       
  }
}

答案 2 :(得分:0)

我确定这是一项任务,但我已经解决了2美分。这个会给你一个数组。

final int EVEN = 0, ODD = 1;
int low = 50, high = 100, current = low;
int[][] numbers = new int[2][];
numbers[EVEN] = new int[((high - low) / 2) + ((high - low) % 2)];
numbers[ODD]  = new int[((high - low) / 2)];
while(current < high){
    numbers[current % 2][(current - low) / 2] = current++;
}
System.out.println("EVEN" + Arrays.toString(numbers[EVEN]));
System.out.println("ODD " + Arrays.toString(numbers[ODD]));

答案 3 :(得分:-1)

替代方法,

int current = 50 , end = 100 ;
String odd , even ;
while(current <= 100){

    if (current % 2 == 0)   
        even = even.concat ("," + current);
    else 
        odd = odd.concat("," + current);
    current++;
}

System.out.println("Even no are : " + even);     
System.out.println("Odd no are : " + odd);

我现在没有编译器。我认为这应该是正确的:)。

相关问题