【问题标题】:java using NetBeans IDE 8.0.2使用 NetBeans IDE 8.0.2 的 java
【发布时间】:2015-07-29 08:03:40
【问题描述】:

我在清除案例 2 和案例 3 的第二行预期的以下错误 '(' 或 '[' 时遇到问题。我编写的代码是 newAnimal.displayInfo();

我不确定为什么我在案例 2 和 3 中收到此错误,但在案例 1 中没有。不确定我做错了什么。任何帮助/指导将不胜感激。

代码如下:

package animalinfo;

import java.util.Scanner;

public class AnimalInfo 
{

/**
 * @param args the command line arguments
 */

public static void main(String[] args)
{
    // TODO code application logic here
    Scanner input = new Scanner (System.in);
    Animal newAnimal;
    int quit = 4;
    while(-4 != quit);
    {
        System.out.println("\n1) Camel" +
                "\n2)Penguin" +
                "\n3) Tortoise" +
                "\n4) Exit Program.");
        System.out.print("Please select an amimalfrom the list.");

        int choice = input.nextInt();
        switch (choice)    
    {    
        case 1: 
            newAnimal = new Camel();
            newAnimal.displayInfo();
            break;
        case 2:
            newAnimal = new Penguin
            newAnimal.displayInfo();
            break;
        case 3:
            newAnimal = new Tortoise
            newAnimal.displayInfo();
            break;     

        case 4:
            System.out.println ("Thank you for making your selections.");
            break;
    }
    }
}
}

【问题讨论】:

    标签: java


    【解决方案1】:
    while(-4 != quit); 
    

    去掉分号,应该只是

    while (-4 != quit) 
    { 
        /*Code here*/ 
    } 
    

    是的,当您有 new Penguinnew Tortoise 时,您缺少括号和分号

    【讨论】:

    • 谢谢!有时似乎是小事让我绊倒。作为一个初学者,我意识到细节是多么的重要。再次感谢!您的反馈非常有帮助。
    【解决方案2】:

    在创建新对象后,您似乎缺少括号。所以这个:

    newAnimal = new Penguin
    

    应该变成这样:

    newAnimal = new Penguin();
    

    这是因为您将 newAnimal 设置为 Penguin 对象的新实例,并且要创建该新实例,您必须调用 Penguin 类的 constructor 来创建对象。

    另外,正如Jurko 所说,您的 while 循环设置不正确。

    while(-4 != quit);
    

    您必须删除分号,否则循环将无限期地运行而不会执行您在它下面的代码。 while 循环的正确语法是

    while (-4 != quit) {
      // Code to repeat here
    }
    

    【讨论】:

    • 谢谢!我发现您的反馈非常有帮助。我看了这么长时间的代码,没有注意到我忽略的项目。再次感谢!
    猜你喜欢
    • 2015-12-05
    • 1970-01-01
    • 2017-12-28
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 2016-01-13
    • 2015-03-13
    相关资源
    最近更新 更多