在数组中搜索term和if语句

时间:2015-10-08 23:21:22

标签: java

我有代码在字符串中搜索一个术语,并希望它找到它然后计算并输出总数。我正在尝试搜索另一个术语并输出该术语的总和。

例如:

 for(String[] passenger : passengerList) {
     if(passenger[3].equalsIgnoreCase("female")) {
        allFemale++;
        if(passenger[1] != null && Integer.parseInt(passenger[1]) == 1 {
           femaleSurvivors++; 
        }
     }    
     count ++;
 }
 System.out.println("The number of females who survived: ");
 return femaleSurvivors;
}

现在,我想搜索男性并计算发生的次数。没有运气。

1 个答案:

答案 0 :(得分:2)

你真的需要跟踪4件事,性别(m / f)和状态(死/活)。您可以在一个循环中完成所有操作。部分内容可以在循环中捕获,部分内容可以在事后计算。

int survivors = 0;
int femaleSurvivors = 0;
int femaleDeaths = 0;
for(String[] passenger : passengerList) {
    boolean isFemale = false;
    if(passenger[3].equalsIgnoreCase("female")) {
      isFemale = true;
    }
    if(passenger[1] != null && Integer.parseInt(passenger[1]) == 1) {
      survivors ++;
      if (isFemale){
        femaleSurvivors++; 
      }
    } else {
      if (isFemale){
        femaleDeaths++; 
      }
    }

}
int totalPassengers = passengerList.size();
int maleSurvivors = survivors - femaleSurvivors;
int deaths = totalPassengers - survivors;
int maleDeaths = deaths - femaleDeaths;
int males = maleSurvivors + maleDeaths;
int females = totalPassengers - males;

System.out.println("Survivors (Total/M/F): " + survivors + "/" + maleSurvivors + "/" + femaleSurvivors);
System.out.println("Deaths (Total/M/F): " + deaths + "/" + maleDeaths + "/" + femaleDeaths);
System.out.println("Totals (All/M/F): " + totalPassengers + "/" + males + "/" + females);