簡體   English   中英

使用NetBeans IDE 8.0.2的Java

[英]java using NetBeans IDE 8.0.2

我無法清除情況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;
    }
    }
}
}
while(-4 != quit); 

擺脫分號,應該只是

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

是的,當您有new Penguinnew Tortoise ,會丟失括號和分號

創建新對象后,似乎缺少括號。 所以這:

newAnimal = new Penguin

應該變成這個:

newAnimal = new Penguin();

這是因為要將newAnimal設置為Penguin對象的新實例,並且要創建該新實例,必須調用Penguin類的構造函數來創建該對象。

另外,正如Jurko所說,您的while循環設置不正確。

while(-4 != quit);

您必須刪除分號,否則循環將無限期地運行而不執行您在其下的代碼。 while循環的正確語法是

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM