2015-09-07 43 views
1

如何從用戶獲得10個數字並打印出兩個最大數字?我嘗試製作一個程序,用戶需要輸入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); 


     } 

    } 

回答

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; 
    } 
} 
相關問題