2017-06-28 40 views
-1

我的程序允許用戶重複輸入匹配結果,直到用戶輸入「停止」,然後顯示結果。我只需要在'stats [2]'arraylist中找到最高的輸入值,這就是'hometeam得分'。所以如果用戶輸入3個輸入,「曼城:曼聯:2:1 ... 切爾西:阿森納:0:1 ... 埃弗頓:利物浦:1:1」那麼它應該顯示數字'2'因爲它是該陣列中最高的價值。如果這是有道理的?我在底部設置了需要顯示的行。在arraylist元素中查找最大/最小值條目

public static void main(String args[]) { 

    Scanner sc = new Scanner(System.in); 
    ArrayList<String[]> stats = new ArrayList<>(); // initialize a container 
                // to hold all the stats 
    System.out.println("please enter match results:"); 

    int matchesPlayed = 0; 
    int invalidEntry = 0; 

    while (sc.hasNextLine()) { 

     String input = sc.nextLine(); 
     String[] results = input.split("\\s*:\\s*"); 

     if (results.length == 4) { 
      stats.add(results); 
      matchesPlayed++; 
     } 

     else if (input.equals("stop")) { 
      break; 
     } 

    } // end of while 

    for (int i = 0; i < stats.size(); i++) { 

     if (stats.get(i)[0].trim().isEmpty()) { 
      System.out 
        .println("no home team name entered on the following line:"); 
      invalidEntry++; 
      matchesPlayed--; 
     } 

     else if (stats.get(i)[1].trim().isEmpty()) { 
      System.out 
        .println("no away team name entered on the following line:"); 
      invalidEntry++; 
      matchesPlayed--; 
     } 

     else if (stats.get(i)[2].trim().isEmpty()) { 
      System.out.println("no home score entered on this line"); 
      invalidEntry++; 
      matchesPlayed--; 

     } 

     else if (stats.get(i)[3].trim().isEmpty()) { 
      System.out.println("no away score entered on this line"); 
      invalidEntry++; 
      matchesPlayed--; 
     } 

     try { 
      System.out.println(String.valueOf(stats.get(i)[0]) + " [" 
        + Integer.valueOf(stats.get(i)[2]) + "] " + " | " 
        + (String.valueOf(stats.get(i)[1]) 

        + " [" + Integer.valueOf(stats.get(i)[3]) + "] ")); 

     } catch (Exception e) { 
      // do nothing with any invalid input 
     } 

    } 
    System.out.println(" "); 
    System.out.println("Totals"); 
    System.out.println("-------------------------"); 
    System.out.println("total number of matches: " + matchesPlayed); 
    System.out.println("total number of invalid entries: " + invalidEntry); 
    System.out.println("highest home score: "); 
} 
+0

除「有意義」之外,您沒有提出任何問題。你有什麼問題? – Kon

+0

我的問題是如何找到在我的ArrayList的[2]元素中輸入的最高數字,並將其存儲在一個int中,以便我可以在底部顯示它? – JHurst

+0

你的「問題」看起來像一本食譜來做。爲什麼不按照你的描述去做呢?或者是如何比較int值的問題? – Heri

回答

0

通過它僅有環,設置一個變量等於第一個元素,並在循環如果存在大於變量更高目前,改變變量的值,以一個元件。然後在最後打印變量

+0

你能給我一個例子來看看代碼中的代碼嗎?對不起,我是新來的java – JHurst

+0

@JHurst https://stackoverflow.com/a/1806830/5338668 –

+0

非常感謝Thankyou! – JHurst