如何从用户获取10个数字并打印出两个最大数字

时间:2015-09-07 14:13:14

标签: java

如何从用户那里获得10个数字并打印出两个最大数字?我尝试制作一个程序,从用户那里获取10个数字......在获取10个数字后,它将显示您输入的最大数字,并显示最大数字之前的数字(最高的两个数字)从你输入的10个数字)我无法弄清楚为什么它不工作..所有!!

import java.util.Scanner;


    public class E11 {

        public static void main(String[] args) {
            // TODO Auto-generated method stub

            Scanner scan = new Scanner(System.in);  

            System.out.println("Enter Number " +0 +" : " );
            float scanNumTwo = scan.nextFloat();

            float scanNum = scanNumTwo;
            float lastscan ;
            float maxim = scanNumTwo;
            float lastmax = scanNumTwo;

            for(int i = 1 ; i<=9 ; i++){
                System.out.println("The Last Max " +lastmax +" : " );
                System.out.println("The Maximum Numer Is : "+maxim);

                System.out.println("Enter Number " +i +" : " );
                lastscan = scanNum;
                scanNum = scan.nextFloat();

                if(lastscan >= scanNum && lastscan >= maxim){
                    maxim = lastscan;
                }
                else if(scanNum >= lastscan && scanNum >= maxim){
                    maxim = scanNum;
                }

                else if (scanNum>lastscan && maxim>lastmax){
                    lastmax = lastscan;
                }
                else if (scanNum>lastmax && maxim>lastmax){
                    lastmax = scanNum;
                }

                System.out.println("The Maximum Numer Is : "+lastmax);
                System.out.println("The Maximum Numer Is : "+maxim);




        }
            System.out.println("The Maximum Numer Is : "+lastmax);
            System.out.println("The Maximum Numer Is : "+maxim);


        }

    }

1 个答案:

答案 0 :(得分:2)

您需要跟踪两个最大的数字。您可以像这样初始化它们:

float maxNumb = scan.nextFloat();
float secondMax = scan.nextFloat();
if (secondMax > maxNumb) {
   float temp = maxNumb;
   maxNumb = secondMax;
   secondMax = temp;
}

之后,您可以扫描所有数字(不包含打印件以方便阅读):

for (...) {
   float next = scan.nextFloat();
   // if greater than max, then it's the new max and the old max is the 2nd
   if (next > maxNumb) {
     secondMax = maxNumb;
     maxNumb = next;
   }
   // if it's only greater than the second, then it's the new second.
   else if (next > secondMax) {
     secondMax = next;
   }
}