public static void main (String[] args) {
String pet;
pet = inputString("What pet do you own?");
if (pet.equals("dog"));
{
System.out.println("Dogs are mans best friend!");
}
if(pet.equals("cat"));
{
System.out.println("Cats are very independent");
}
if(pet.equals("lion"));
{
System.out.println("I don't think that should be your pet mate...");
}
}
请帮忙,我的代码没有接受用户的输入,只打印println
行。我如何使用else if
来代码。
答案 0 :(得分:4)
嗯..在Java中,默认情况下我们没有jave inputString
方法。您可以使用Scanner
Scanner sc = new Scanner(System.in);
System.out.println("What pet do you own?");
pet = sc.nextLine();
您还应该记住,Java中的if-else
语句如下所示:
if (<condition>) { //<--there is no ;
//do
} else {
//do
}
没有专门的else if
声明作为elif
或其他任何内容,但您可以使用:
if (<condition>) { //<--there is no ;
//do
} else if (<condition>){
//do
} else if (<another condition>) {
//do
} else {
//do
}
只有if
是强制性的。您可以跳过else
语句。最后,您的代码应如下所示:
public static void main (String[] args) {
String pet;
Scanner sc = new Scanner(System.in);
System.out.println("What pet do you own?");
pet = sc.nextLine();
if (pet.equals("dog")) {
System.out.println("Dogs are mans best friend!");
} else if(pet.equals("cat")) {
System.out.println("Cats are very independent");
} else if(pet.equals("lion")) {
System.out.println("I don't think that should be your pet mate...");
} else {
System.out.println("I didn't recognize your pet");
}
}