2012-08-05 94 views
0

應該運行一個打印最大和次大的程序,但在獲得第二個值時遇到問題。認爲我的布爾表達式是錯誤的,因爲我一直得到0作爲tempSecond。你能幫我嗎?Java的藝術與科學第4章練習13

/* 
* File: AddExamIntegers.java 
* -------------------- 
* This program takes a list of integers until Sentinel, 
* then prints the largest and second largest. 
*/ 

import acm.program.*; 

public class FindLargest extends ConsoleProgram { 


    public void run() { 
     println("This program takes a list of integers and then lists the largest and second largest"); 
     println(""); 
     println("Enter positive numbers using " + SENTINEL); 
     println("to signal the end of the list"); 

     int tempHigh = 0; 
     int tempSecond = 0; 

     while (true) { 
      int value = readInt(": "); 
      if (value == SENTINEL) break; 
       if (tempHigh < value) { 
        tempHigh = value; 
        } 
       if ((tempSecond < value) && (tempSecond > tempHigh)) { 
        tempSecond = value; 
        } 
     } 
     println("The largest value is " + tempHigh); 
     println("The second largest value is " + tempSecond); 
    } 

    private static final int SENTINEL = 0; 

} 
+0

'如果(tempHigh <值)'那麼你已經找到了新高但你之前的高位是你的新的第二位。 – assylias 2012-08-05 09:37:54

回答

3

你的後面,如果將永遠不會真正的第二部分:tempSecond > tempHigh

相反,這樣做:

 if(tempHigh < value) 
     { 
      tempHigh = value; 
     } 
     else if(tempSecond < value) 
     { 
      tempSecond = value; 
     } 
+0

謝謝esaj,但我試過。從我所看到的情況來看,在tempHigh成爲最高值之後,第一個if語句在任何時候都不再是真實的,因此,tempSecond值將永遠不會被重置。 – aldangerduncan 2012-08-05 10:19:24

+0

@aldangerduncan:不錯,沒有想直,看到我編輯的答案。 – esaj 2012-08-05 10:24:13

+0

ahhhhh,那就是訣竅!謝謝 – aldangerduncan 2012-08-05 10:27:27