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");}
8 ответов
+ 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");
}
+ 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).
+ 3
if(!animal.equalsIgnoreCase("dog") && !animal.equalsIgnoreCase("cat") && !animal.equalsIgnoreCase("dog"))
But in your case, you can also just use else{...}
+ 2
Try if it works when you replace + with ||
+ 1
thank you but it didnt work, it works with just one string? is there a better way to do this?
+ 1
thanks guys @ maart the && worked a treat thanks! @faith i will try the else function next time lol thanks!
+ 1
@ chaotic oh wow that alot easier haha thanks
+ 1
Just also know that String values can not be used in a switch statement in earlier versions of java.