2017-10-28 39 views
0

我是新來的Java,我與我的Loops.I掙扎想創建一個基本的程序,將分析投注results.My燈具類的構造函數:我需要遍歷Java中的arrayList,並將返回的結果相乘。我與返回結果的乘法掙扎

public Fixtures(String homeTeamName,double homeTeamOdds,String 
    awayTeamName, double awayTeamOdds,double drawOdds,String result) { 
    this.homeTeamName=(homeTeamName); 
    this.homeTeamOdds=(homeTeamOdds); 
    this.awayTeamName=(awayTeamName); 
    this.awayTeamOdds=(awayTeamOdds); 
    this.drawOdds=(drawOdds); 
    this.result=(result); 
} 

通過ArrayList的

Fixtures fixture2= new Fixtures("ManchesterUnited",1.6,"Spurs",3.1,2.8,"home"); 
Fixtures fixture3= new Fixtures("Manchester Citeh",1.3,"Burnley",4.1,3.8,"home"); 
Fixtures fixture4= new Fixtures("Newcastle",2.1,"Bomouth",4.1,2.6,"away"); 
Fixtures fixture5= new Fixtures("Everton",2.1,"Watford",4.6,2.3,"away"); 
Fixtures fixture6= new Fixtures("Chelsea",2.1,"Brighton",4.1,3.8,"draw"); 

ArrayList<Fixtures> games = new ArrayList<Fixtures>(); 

games.add(fixture2); 
games.add(fixture3); 
games.add(fixture4); 
games.add(fixture5); 
games.add(fixture6); 

現在我想環路,並找到固定在那裏,結果是一個「家」贏得繁衍主場獲勝賠率together.What我有如下打印:我創建燈具對象的ArrayList淘汰了2個主場球隊。我想然後把它們放在一起。我對完成這個循環stuck.Any幫助將不勝感激

double x=0; 
for (int i = 0; i < games.size(); i++){ 
    if (games.get(i).getResult().equals("home")){ 
     x=(games.get(i).getHomeTeamOdds()); 

     System.out.println(x); 
    } 

回答

3

您需要將您的變量初始化爲1,因爲乘以0是沒有意義的。您的「家」檢查是好的,只是繁衍getHomeTeamOdds()結果與x

double x = 1; 
for (int i = 0; i < games.size(); i++) { 
    if (games.get(i).getResult().equals("home")) { 
     x *= games.get(i).getHomeTeamOdds(); 
    } 
} 

而不是使用醇」斯庫爾方法,你也可以使用Java流API:

double d = games.stream() 
    .filter(t -> Objects.equals(t.getResult(), "home")) 
    .mapToDouble(t -> t.getHomeTeamOdds()) 
    .reduce(1, (a, b) -> a * b); 

在我看來,你的操作意圖更清晰。

  • .filter(t -> Objects.equals(t.getResult(), "home"))對結果爲「home」的所有元素進行過濾,丟棄所有其他元素;
  • .mapToDouble(t -> t.getHomeTeamOdds())選擇所有homeTeamOdds值;
  • .reduce(1, (a, b) -> a * b)對收集的值應用數學縮減,其中1作爲初始值,並將縮減操作作爲lambda表達式:將每個元素與先前的結果相乘。
+0

謝謝你什麼。我必須看看Java Streams API。我從來沒有用過它。 – CMAC

0

這應該給你你想要

Fixtures fixture2 = new Fixtures("ManchesterUnited", 1.6, "Spurs", 3.1, 2.8, "home"); 
    Fixtures fixture3 = new Fixtures("Manchester Citeh", 1.3, "Burnley", 4.1, 3.8, "home"); 
    Fixtures fixture4 = new Fixtures("Newcastle", 2.1, "Bomouth", 4.1, 2.6, "away"); 
    Fixtures fixture5 = new Fixtures("Everton", 2.1, "Watford", 4.6, 2.3, "away"); 
    Fixtures fixture6 = new Fixtures("Chelsea", 2.1, "Brighton", 4.1, 3.8, "draw"); 

    ArrayList<Fixtures> games = new ArrayList<Fixtures>(); 

    games.add(fixture2); 
    games.add(fixture3); 
    games.add(fixture4); 
    games.add(fixture5); 
    games.add(fixture6); 

    double x = 1; 
    for (Fixtures game : games) 
     if (game.getResult().equals("home")) { 
      x *= game.getHomeTeamOdds(); 
     } 

    System.out.print(x); 
+0

非常感謝。 – CMAC