+ 2

Why doesn't this read my string please? I keep getting "animal unknown" 😕 thanks

String animal; Scanner scan = new Scanner(System.in); animal = scan.nextLine(); if(animal == "frog"){ System.out.print("Croak!");} if(animal == "dog"){ System.out.println("Woof!");} if(animal == "cow"){ System.out.println("Moo!"); }else{ System.out.println("Animal unknown");}

10th Jun 2017, 12:28 PM
D_Stark
D_Stark - avatar
6 Answers
+ 4
I think it's because you use ==. If you compare 2 strings you should use .equals or .equalsIgnoreCase and than it should work :)
10th Jun 2017, 12:39 PM
FyremanMusic
FyremanMusic - avatar
+ 3
if (animal.equalsIgnoreCase("frog")){ //what the frog says }
10th Jun 2017, 1:18 PM
FyremanMusic
FyremanMusic - avatar
+ 1
can you give me an example as to were i insert .equals thanks
10th Jun 2017, 1:15 PM
D_Stark
D_Stark - avatar
+ 1
thanks now i just need to figure out if an animal string is unknown then to output "unknown animal". i tried>> if(!animals.equalsIgnoreCase("frog" + "cow" + "dog" )){System.out.println("unknow animal");} but didnt work and printed "croak" "animal unknown" 😕 can you help with that? thanks
10th Jun 2017, 5:36 PM
D_Stark
D_Stark - avatar
+ 1
Do if ( condition 1){ } else if (condition 2){ } else if (condition n){ } else { // what's supposed to happen if it's none of the above } there u go ;)
10th Jun 2017, 7:18 PM
FyremanMusic
FyremanMusic - avatar
- 1
Why are you concatenating frog,cow and dog? Use and for final condition.
10th Jun 2017, 9:59 PM
Mahad Jamal