對不起,我被困在轉換這做while while循環可以請任何人幫助我。java如何轉換爲循環做while循環
int sum = 0;
int num;
System.out.print("Enter number: ");
num = sc.nextInt();
// Store the user input into variable num
// Complete the for loop to start from 1
// and end at num
for (int i = 1 ; i <=num ; i++)
sum += i;
System.out.println("The sum is " + sum);
,這是我的do while循環
int sum = 0;
int num;
int i = 1;
do {
sum += i;
System.out.print("Enter number: ");
num = sc.nextInt();
i++;
} while (i <= num);
System.out.println("The sum is " + sum);
你的while循環執行num + 1次。 – Maroun
當你的輸入*在for循環和*在while循環中時,你可能會有不同的行爲。 – Filburt
'for'循環首先檢查條件以查看它是否可以迭代,'do-while'首先迭代,然後檢查條件是否應該再次迭代。如果你想要有完全相同的行爲,你需要在輸入'do-while'之前添加條件檢查,但是在這一點上它意味着你應該簡單地使用'while {}'循環。 – Pshemo