0

Is there an easy way to do this please? Im new and i dont understand why if(! Is not working if string is unknown. Thanks!

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

10th Jun 2017, 5:29 PM
D_Stark
D_Stark - avatar
8 Réponses
+ 1
"dog" + "cat" + "cow" results in String concatenation and ends up comparing to "dogcatcow" instead of each individual String. What you really have here is a switch statement. Scanner scan = new Scanner(System.in); String animal = scan.nextLine(); switch (animal.toLowerCase()) { case "frog": System.out.println("Croak!"); break; case "dog": System.out.println("Woof!"); break; case "cow": System.out.println("Moo!"); break; case "cat"; System.out.println("Meow!"); break; default: System.out.println("Unknown animal"); }
10th Jun 2017, 6:38 PM
ChaoticDawg
ChaoticDawg - avatar
+ 3
Instead of the !equalsIgnoreCase....etc.. Why not just use else? Then for the other if statements use an else if statement instead of if. (Only the first statement would be an if).
10th Jun 2017, 6:00 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
if(!animal.equalsIgnoreCase("dog") && !animal.equalsIgnoreCase("cat") && !animal.equalsIgnoreCase("dog")) But in your case, you can also just use else{...}
10th Jun 2017, 6:01 PM
Maart
Maart - avatar
+ 2
Try if it works when you replace + with ||
10th Jun 2017, 5:49 PM
Maart
Maart - avatar
+ 1
thank you but it didnt work, it works with just one string? is there a better way to do this?
10th Jun 2017, 5:57 PM
D_Stark
D_Stark - avatar
+ 1
thanks guys @ maart the && worked a treat thanks! @faith i will try the else function next time lol thanks!
10th Jun 2017, 6:07 PM
D_Stark
D_Stark - avatar
+ 1
@ chaotic oh wow that alot easier haha thanks
10th Jun 2017, 6:43 PM
D_Stark
D_Stark - avatar
+ 1
Just also know that String values can not be used in a switch statement in earlier versions of java.
10th Jun 2017, 6:47 PM
ChaoticDawg
ChaoticDawg - avatar