我提前道歉;我無法在Search中找到這個簡單問題的答案。Java「while」循環 - 計數匹配Algo - 賦值必須發生在while循環內
我是編碼的新手。目前Udacity正在通過Java Intro入門課程。
有些東西我不理解,因爲它涉及某些算法。例如
以「計數匹配」算法爲例。
double input = in.nextDouble()的賦值;需要在while循環內部發生。
如果我把它放在while循環的上面,它會破壞程序。爲什麼?
在我看來,Java不應該關心值何時存儲在變量中。
import java.util.Scanner;
public class CountingMatches
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
int counter = 0;
System.out.print("Enter a value, Q to quit: ");
// double input = in.nextDouble(); // remember to place the assignment of this variable inside the while loop.
// I tend to want to place this outside the while loop because I still don't
// understand why it necessarily must occur inside the while loop.
while (in.hasNextDouble())
{
double input = in.nextDouble(); // this assignment is properly located here as opposed to just above the while-loop
if (input < 0)
{
counter++;
}
System.out.print("Enter a value, Q to quit: ");
}
System.out.println("The water line fell on " + counter + " years.");
}
}
你是不是認爲'hasNextDouble()'永遠不會是錯誤的? – SomeJavaGuy
@KevinEsche是啊,也考慮到'掃描儀'的工作方式,答案是無論如何都有誤導 – Matt