簡體   English   中英

為什么我的程序在循環時不打印偶數?

[英]Why is my program not printing even numbers do while loop?

我創建了一個do while循環,即使使用modjule符號,它仍然無法從列表中打印偶數,這是怎么回事?

  int w=1;
    do {
    Scanner keyboard = new Scanner(System.in);
    System.out.println(w);
    w++;
    if(w%2==0);   

    } 
    while (w<=2015);

   }
}

您的代碼應該是

int w=1;
    do {
    Scanner keyboard = new Scanner(System.in);
    System.out.println(w);
    if(w%2==0)
    System.out.println("Even value : "+ w);
    w++;
    } 
    while (w<=2015);

   }
}

if語句后刪除分號

  if(w%2==0); <- Remove this semicolon

並在if語句中獲取或打印偶數。

  if(w%2==0){
     System.out.println("Even valud is "+ w)        
  }

對於均勻測試,我更希望按位&操作以提高性能。

 if((w & 1) ==0){// & is more faster than %
     System.out.println("Even valud is "+ w)        
  }

這非常簡單,可能已經在注釋中得到了答案,但這是一個更完整的代碼塊:

Scanner keyboard = new Scanner(System.in); // you never use this, why is it here?
int w=1;
do {
    w++;
    if(w % 2==1) 
        System.out.println("Odd: " + w);
    else System.out.println("Even: " + w);
} while (w <= 2015);

您可能應該查看此代碼的所有部分,並確保您看到它的實際工作原理以及錯誤的出處。

暫無
暫無

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

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