布尔函数无法正常工作

时间:2014-06-19 13:58:51

标签: java function interface boolean

我有这个小小的程序,为了好玩,想看看界面是如何工作的。当我在eatsOrNot函数中输入“iarba”时,对于dog对象,我知道,当我应该得到假的时候。我在布尔函数中做错了什么?

package animals;

    public interface Actions {


 void Sound();
 boolean eatsOrNot(String s);
 void guessNumberOfLegs(int x );


 }


 package animals;

 public class Dog implements Actions {



 public boolean eatsOrNot(String s)
 {
     if (s=="paine"||s=="morcovi"||s=="iarba") return false;
     else return true;

 }


public void Sound() {
    System.out.println("Dog goes 'woof'");
}

public void guessNumberOfLegs(int x) {
    if (x==4) 
        System.out.println("Right!");
    else    System.out.println("Wrong!");
}


           }




package animals;

public class Rabbit implements Actions {



     public boolean eatsOrNot(String s)
     {
         if (s=="fier") return false;
         else return true;
     }


    public void Sound() {
        System.out.println("Rabbit goes bla");
    }

    public void guessNumberOfLegs(int x) {
        if (x==4) 
            System.out.println("Right!");
        else    System.out.println("Wrong!");
    }


}



package animals;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;


public class TestAnimals {

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        Scanner in= new Scanner(System.in);
        BufferedReader in1=new BufferedReader(new InputStreamReader(System.in)); 
        Dog dog=new Dog();
        Rabbit rabbit=new Rabbit();

        System.out.println("Rabbit sound:" );
         rabbit.Sound();
         System.out.println("Dog sound:" );
         dog.Sound();

         System.out.println("Guess number of a dog's legs:" );
           int legs=in.nextInt();
           dog.guessNumberOfLegs(legs);
           System.out.println("Guess number of a rabbit's legs:" );
            legs=in.nextInt();
           dog.guessNumberOfLegs(legs);


           System.out.println("The dog eats or not : ");
                String str=in1.readLine();
               dog.eatsOrNot(str);
               System.out.println(dog.eatsOrNot(str));

           System.out.println("The rabbit eats or not : ");
           String str1=in1.readLine();
           rabbit.eatsOrNot(str1);
           System.out.println(rabbit.eatsOrNot(str1));








    }

}

2 个答案:

答案 0 :(得分:0)

您正在使用String比较==。请改用equals方法。

答案 1 :(得分:0)

不要将字符串与==进行比较,但要使用方法equals()

public boolean eatsOrNot(String s)
{
    if (s.equals("paine") || s.equals("morcovi") || s.equals("iarba")) return false;
    else return true;
}