簡體   English   中英

我如何終止這個循環?

[英]How do I terminate this loop?

“只應使用一個 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;

    }       
  }
}

偶數打印得很好,但賠率永遠持續下去。 這可能是一個愚蠢的問題,但我現在腦放屁最大,我真的很感激這方面的幫助。

也許你應該試試這個

    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;
        }

    }

試試這個,讓我知道。 它基於您的代碼,只需進行一些小調整:

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 美分,因為它已經解決了。 這個會給你一個數組。

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]));

替代方法,

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);

我現在沒有編譯器。 我認為這應該是正確的 :) 。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM