查看此代碼?使用掃描儀輸入的所有for循環參數
import java.util.Scanner;
public class CountingMachineRevisited {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int from, to, by;
System.out.print("Count from: ");
from = scan.nextInt();
System.out.println("Count to: ");
to = scan.nextInt();
System.out.println("Count by: ");
by = scan.nextInt();
for (int i = from; i <= to; i+=by) {
System.out.println(i);
}
}
}
此代碼我希望它的方式,但如果我改變的終止條件爲循環來我==來,它不工作。
for (int i = from; i == to; i+=by) {
System.out.println(i);
}
我會明白這一切都是整型的默認爲0使終端一樣的初始所以for循環將停止,但如果我在循環之前初始化新的價值觀開始爲什麼犯規工作?
當'i'獲得值'from'時,它不等於'to',所以循環從不執行。用'from'等於'to'來試試你的程序,你會發現它只會進入for循環一次。 – Tunaki
那麼你初始化你的變量是什麼?根據你的變量,'i + by'可能會跳過'to'的值 – Zarwan
如果我初始化它們:從= 1到= 10,by = 2。如果終止條件是「我==爲「。我意識到如果輸入沒有正確輸入,循環會變得混亂。我很好奇它爲什麼永遠不會執行。 –