如何通过将输入字与String数组Java中的元素进行比较来获得结果

时间:2017-03-16 18:18:35

标签: java

所以我想要实现的是当我写一个像#34; Meat"根据输入的要求,该方法将检查关系,并将为#34; Meat"运行相应的结果,如果是"肉"是输入" woof"应该打印。但执行时没有任何反应。我必须告诉我,我是Java和编程的新手。谢谢你的耐心等待!

 package animals;

    import java.util.Scanner;

    public class Animal {

    public int hungerLvl = 0;   
    public String food;
    public String[] foodTypes = {"Meat" , "Grass", "Water"};
    Scanner in = new Scanner(System.in);

    public void  eatFood(){

       System.out.println("Enter food: ");
       food = in.nextLine();    
       if(food == foodTypes[0].toString()){
          System.out.println("woof");
          hungerLvl++;
          System.out.println("Hunger lvl incresead to " + hungerLvl);
       } else {
           if (food == foodTypes[1].toString()){
               System.out.println("Animal is eating grass");
               hungerLvl++;
           }
           if (food == foodTypes[2].toString()){
               System.out.println("Animal is drinking water");
               hungerLvl++;
           }           
       }  
    }
    //ignore this method :)
    public int maxLvl(){
       if(hungerLvl == 5){
           System.out.println("No more food, going to take a nap!");
           hungerLvl = hungerLvl - 5;
       }
       return 0;
    }

     public static void main(String[] args){
        Animal animal = new Animal();

     animal.eatFood();
     }
     }

1 个答案:

答案 0 :(得分:0)

使用str.equals或str.match

   public void  eatFood(){
   System.out.println("Enter food: ");
   food = in.nextLine();    
   if(food.matches(foodTypes[0])){
      System.out.println("woof");
      hungerLvl++;
      System.out.println("Hunger lvl incresead to " + hungerLvl);
   } else {
       if (food.matches(foodTypes[1])){
           System.out.println("Animal is eating grass");
           hungerLvl++;
       }
       if (food.matches(foodTypes[2])){
           System.out.println("Animal is drinking water");
           hungerLvl++;
       }           
   }  
}