java—将对象列表调用到方法中以检查枚举值

30byixjq  于 2021-07-12  发布在  Java
关注(0)|答案(1)|浏览(357)

我是java新手,有一个名为 listPlayer 这是样品

Player{FirstName='Marco', LastName='Reus', Team='Dortmund', Country='Germany', Fitness='Unfit', RecoveryTime='Slow'}

我也有一个枚举值的健身水平范围

public enum LevelOfFitness {
/**
 * Enum that represent the different level of Fitness of each player
 */

    CAREER_IN_DOUBT(8), INDEFINITELY_INJURED(7), INJURED(6), UNFIT(5), CLOSE_TO_FITNESS(4), 
NEAR_MATCH_FIT(3),
    MATCH_FIT(2), DATA_DEFICIENT(1), NOT_EVALUATED(0);

private int value;

LevelOfFitness (int aValue) {
    this.value = aValue;
}

public int getValue () {
    return value;
}

}
我还有一个方法,可以循环检查 listPlayer 与枚举值中找到的相同。

public LevelOfFitness from(String value){  

  LevelOfFitness found = null;
  for(LevelOfFitness level : LevelOfFitness.values()){
      if(level.name().equalsIgnoreCase(value)){
         return level;
      }
  }

   throw new IllegalStateException("Not able to find fitness level for " + value);
}

我正在努力理解如何将这个枚举方法调用到我的main和call中 listPlayer 进入循环,这样它可以返回一个健康水平。例如,第一个球员循环通过检查水平(不适合),并返回5作为水平非常感谢。

mkh04yzy

mkh04yzy1#

我假设你 from(String) 方法在中声明 enum LevelOfFitness .
你关心我吗 from(String)static 方法,调用如下: LevelOfFitness.from("string"); ;

public static void main(String[] args){

    List<Player> playerList = new ArrayList<>();
    playerList.add(new Player("Marco", "Reus", "Dortmund", "Germany", "Unfit", "Slow"));
    playerList.add(new Player("Name1", "Name2", "Team1", "Country1", "not_evaluated", "time1"));
    playerList.add(new Player("Name1", "Name2", "Team1", "Country1", "error_fitness", "time1"));

    for(Player player : playerList){

        try{

            LevelOfFitness lof = LevelOfFitness.from(player.getFitness());
            System.out.println(lof.getValue());

        }catch(Exception e){
            e.printStackTrace();
        }

    }

}

----- output -----
5
0
java.lang.IllegalStateException: Not able to find fitness level for error_fitness

相关问题