2013-11-04 50 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

它仍然是:)。 –