[英]I don't understand this Java while loop
我對這個 while 循環感到困惑。 如果條件為真,則重復; 如果為假,則結束循環。 那正確嗎?
int a = in.nextInt();
int num;
int highestDigit = 0;
while (a > 0) {
int digit = a % 10;
if (digit > highestDigit) {
highestDigit = digit;
}
a /= 10;
}
System.out.println(highestDigit);
但是,條件為真,因此它會一遍又一遍地打印最高數字。 但是代碼在找到最高位時停止。
輸入:214 輸出:4
使用像 Eclipse 這樣像樣的 Java IDE,使用它的調試器並單步執行程序,密切關注變量。
或者,為了更深入地理解這樣的程序,拿一張長紙並在你的大腦中模擬程序(當前指令加上該指令產生的變量值):
instruction a highestDigit digit remark
-----------------------------------------------------------------------------
int a = in.nextInt(); 214 - -
int highestDigit = 0; 214 0 -
while (a > 0) { 214 0 - is true: enter loop
int digit = a % 10; 214 0 4
if (digit > highestDigit) { 214 0 4 is true: enter block
highestDigit = digit; 214 4 4
a /= 10; 21 4 4
while (a > 0) { 21 4 - is true: enter loop
int digit = a % 10; 21 4 1
等等...
首先,您應該使用一個非常有希望的調試器,然后我更改了您的代碼:
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
int a = sc.nextInt();
int num ;
int highestDigit = 0;
while (a > 0) {
int digit = a % 10;
if (digit > highestDigit) {
highestDigit = digit;
}
a /= 10;
System.out.println("highestDigit is : " + highestDigit);
}
System.out.println(highestDigit);
}
}
我想如果你運行我提到的代碼,你就會得到答案。
你沒有一次又一次地看到highestDigit,因為你在while循環之后使用System.out.print
,所以它只打印for循環之后建立的highestDigit。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.