2012-04-06 127 views
0

我需要從這段代碼中獲得最大值,但它確實很棘手。任何人有任何建議?獲取「用戶輸入的最大值」?

import java.util.Scanner; 
public class Test{ 
    public static void main(String args[]) 
    { 
     Scanner scan = new Scanner(System.in); 

     final int sentinel = 0; 
     int number; 
     int maxval = 0; 
     int count = 0; 

     System.out.println ("Enter a number: "); 

     number = scan.nextInt(); 
     while (number != sentinel) 
     { 
      count++; 
      System.out.println("Enter another number"); 
      number = scan.nextInt(); 
      maxval = number; 
     } 

     if (number > maxval) 
     { 
      maxval = number; 
      System.out.println ("The max value is " + maxval); 
     } 
    } 
} 
+0

刪除'while'裏面的'maxval = number'並在循環中獲得條件語句 – mshsayem 2012-04-06 01:31:41

回答

1

您每次獲得新號碼時都會覆蓋maxval變量。你必須做這樣的事情

while (number != sentinel) 
{ 
    count++; 
    System.out.println("Enter another number"); 
    number = scan.nextInt(); 
    if (number > maxval && number != sentinel) //So you don't overwrite it when you get the sentinel character 
     maxval = number; 
} 
System.out.println ("The max value is " + maxval); 
+0

謝謝你們!絕對需要改進我的循環結構... – jerms246 2012-04-06 01:36:39

0

試試這個,這是一個有點簡單,修復了代碼的主要問題:比較number > maxval必須主循環中:

Scanner scan = new Scanner(System.in); 

    final int sentinel = 0; 
    int maxval = 0; 
    int number = 0; 

    do { 
     System.out.print("Enter a number: "); 
     number = scan.nextInt(); 
     if (number > maxval) 
      maxval = number; 
    } while (number != sentinel); 

    System.out.println("The max value is " + maxval);