2013-11-04 76 views
0

的問題是:第一和第二大的量

編寫一個程序,提示用戶輸入5個號碼,以及它們之間找到 兩個最大的價值。如果用戶輸入的數字超過100 或小於-100,程序應該退出。

Hint: use break. 

我的代碼是:

import java.util.*; 

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

     int num; 
     int max=0;//define Maximum value and save it in variable max = 0; 
     int secondMax=0;//define the second maximum value and save it in variable secondMax = 0; 

     System.out.println("Please , Enter 5 numbers between 100 and -100 "); //promet user to enter 5 numbers with the condition 

     for (int count=0 ; count<5 ; count++) // start loop with (for) 
     { 
      num = scan.nextInt();//user will enter number it will be repeated 5 times . 

      if(num > 100 || num<-100) //iv the user enter a number less than -100 or geater than 100 program will quit from loop 
      { 
       System.out.println("The number you have entered is less than -100 or greater than 100 ");//telling the user what he did 
       break;//End the loop if the condition (num > 100 || num<-100) is true . 
      } 
      if(num>max)//Another condition to find the maximum number 
       max = num;//if so , num will be saved in (max) 

      if (num >= secondMax && num < max)// A condition to find the second Maximum number 
       secondMax = num;//And it will be saved in (secondMax) 
     }//End loop 
     System.out.println("The largest value is " + max); //Print the largest number 
     System.out.println("The second largest value is " + secondMax);//print the second largest number . 
    }//End main 

}//End class 

這是我的代碼輸出:第二大數字是

Please , Enter 5 numbers between 100 and -100 
20 
30 
60 
20 
-10 
The largest value is 60 
The second largest value is 20 

不正確 - 20,而不是30我做了什麼錯誤?

+3

你失去了30,因爲它被替換爲60而沒有被複制到'secondMax'。我想,你應該把這個添加到第一個'if'子句。 –

回答

0
if(num>max)//Another condition to find the maximum number 
secondMax = max; 
    max = num;//if so , num will be saved in (max) 

else if (num >= secondMax)// A condition to find the second Maximum number 
secondMax = num;//And it will be saved in (secondMax) 
3

可以有兩種情況,

  1. 你找到新的最大值,在這種情況下,更新secondmax並將此NUM爲最大
  2. 你找到新的SecondMax,只更新secondmax

試試這個

if(num>secondMax&&num<max) // case 2 
{ 
    secondMax = num 
} 
else if(num>max) // case 1 
{ 
    secondMax = max; 
    max = num; 
} 
0

如果您將最高的數字替換爲更高的數字,前者最大的一個成爲第二大(因爲它仍然比前第二大)。你的代碼並不反映這一點。 每次你改變最大的nubmer時,將第二大號設置爲舊的最大號。

0

在此條件下,其中的最大數量變化先保存先前的最高比分配新的最大否則第二最高應調整如果不到的數量。

if(num>max){//Another condition to find the maximum number 
    secondmax = max; 
    max = num;//if so , num will be saved in (max) 
} else if (num > secondmax) { 
    secondmax = num; 
} 
+0

不行,如果max = 9且secondmax = 8且新數字爲10,則代碼將生成10和8作爲max和secondmax,這是錯誤的 –

+0

@AnkitRustagi yes第一眼看起來是錯誤的。 – 2013-11-04 19:05:24

+0

它仍然是:)。 –