0

I have this tiny little program made for fun, wanted to see how interfaces work . When I enter " iarba " onto the eatsOrNot function, for the dog object, I get true , when I am supposed to get false. What am I doing wrong in that boolean function ?

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));








    }

}
123123d
  • 195
  • 2
  • 14

2 Answers2

0

You're comparing Strings using ==. Use the equals method instead.

Ray
  • 3,084
  • 2
  • 19
  • 27
0

Don't compare Strings with ==, but with method equals().

public boolean eatsOrNot(String s)
{
    if (s.equals("paine") || s.equals("morcovi") || s.equals("iarba")) return false;
    else return true;
}
AntonH
  • 6,359
  • 2
  • 30
  • 40