2014-03-02 67 views
-2

試圖獲得此輸入5個不同的溫度讀數,並輸出最低的輸入。 Im new to java使用循環輸入

System.out.println("Enter 5 temperature readings"); 
Scanner input = new Scanner(System.in); 



int count = 1; 
while (count <= 5){ 
    int temp = input.nextInt(); 
    if (temp < temp){ 
    low = temp; 
    } 

    count++; 

} 
System.out.println(------); 
+0

你的問題是什麼?什麼不行?爲什麼?你期望它做什麼? – BackSlash

+1

你的問題是什麼?你的代碼有什麼問題? –

+0

你的問題在哪裏? –

回答

1

我只是繼續前進,並認爲這是您的所有相關代碼。如果是這樣,那麼你有兩個問題。第一個問題是你永遠不會宣佈低點。我建議在聲明計數之前或之後聲明低位爲int。你有的第二個問題是你正在比較自己的溫度。 temp永遠不會少於temp,所以基本上你正在創建一個永遠不會運行的代碼塊。你應該寫的是temp <低。這裏是你的代碼進行必要的修改。

System.out.println("Enter 5 temperature readings"); 
Scanner input = new Scanner(System.in); 



int count = 1; 
int low = input.nextInt(); //the lowest value cannot possible be higher than this. 
while (count <= 4){ //made the loop shorter because one value was already read. 
    int temp = input.nextInt(); 
    if (temp < low){ 
    low = temp; 
    } 

    count++; 

} 
System.out.println(low); 

我離開while循環,因爲它在技術上是正確的,但你真的應該在這裏使用一個for循環。 (http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

2

首先,你從來沒有實例化你的變量low。此外,我們需要在循環外部需要low,所以請確保這些變量在循環之外實例化,因此我們可以在輸出low時使用它們。所以讓我們這樣做

int low = Integer.MAX_VALUE; 

您可能會問「爲什麼Integer.MAX_VALUE?」這是因爲1)變量low在用於比較之前必須被初始化,並且2)我們不能使用0,因爲如果溫度不低於0,則0將是低的! Integer.MAX_VALUE是int可容納的最高值,因此它遠高於低溫。

接下來,讓我們看看你的條件,在這裏我已經看到了問題:

if (temp < temp) 

你比較temptemp,這是同樣的事情!這意味着這個條件永遠不會是真的。你想要使用的是什麼

if (temp < low) 

這樣就可以正確記錄低溫。接下來,一旦low通過使用

System.out.println(low); 

這應該給你五個輸入值的低溫計算,可以輸出low

重構機遇

如果你想使你的代碼更加清晰,我建議使用for循環,而不是您所使用的while循環。這樣,您的循環將變爲

for (int i = 0; i < 5; i++) 
{ 
    //your logic here 
} 

這意味着不需要count變量。