【问题标题】:(Cannot find symbol - method inputString(java.lang.String) Help why is there this error? [closed](找不到符号 - 方法 inputString(java.lang.String) 帮助为什么会出现此错误?[关闭]
【发布时间】:2016-10-17 11:20:55
【问题描述】:
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

【问题讨论】:

标签: java compiler-errors


【解决方案1】:

嗯.. 在 Java 中,我们默认不使用 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");
    }

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多