(找不到符号 - 方法inputString(java.lang.String)帮助为什么会出现这个错误?

时间:2016-10-17 11:20:56

标签: java compiler-errors

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来代码。

1 个答案:

答案 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");
    }

}