2014-10-12 91 views
0
import javax.swing.*; 
public class Menu2 { 

    protected String[] entreeChoice = {"Rosemary Chicken", "Beef Wellington", "Maine Lobster"}; 
    private String menu = ""; 
    private int choice; 
    protected char initial[] = new char[entreeChoice.length]; 


    public String displayMenu(){ 

     for(int x = 0; x < entreeChoice.length; ++x){ 
      menu = menu + "\n" + (x+1) + "for" + entreeChoice[x]; 
      initial[x] = entreeChoice[x].charAt(0); 
     } 
     throws menuException 


     String input = JOptionPane.showInputDialog(null, "Type your selection, then press Enter." + menu); 
     choice = Integer.parseInt(input); 
     return (entreeChoice[choice - 1]); 
    } 

} 

我在throws menuException上遇到錯誤。它說:非法啓動類型。 我幾乎完成了代碼,只是代碼需要修改(附圖),當我這樣做時,我會在代碼的放置位置出錯。修改java代碼錯誤

photo of code

回答

2

取決於你想要做什麼(拋出一個異常,或宣佈你的方法可能會拋出這種類型的異常):

要麼改變它太:

public String displayMenu() throws menuException { 

    for(int x = 0; x < entreeChoice.length; ++x){ 
     menu = menu + "\n" + (x+1) + "for" + entreeChoice[x]; 
     initial[x] = entreeChoice[x].charAt(0); 
    } 
    ... 
} 

或者:

public String displayMenu(){ 

    for(int x = 0; x < entreeChoice.length; ++x){ 
     menu = menu + "\n" + (x+1) + "for" + entreeChoice[x]; 
     initial[x] = entreeChoice[x].charAt(0); 
    } 
    if (someCondition) 
     throw new menuException(); 
    ... 
} 
+0

@Dan想想吧,後者將不起作用,因爲'throw new ...'後面的代碼將變得無法訪問。編輯答案。 – Eran 2014-10-12 11:08:14

+0

現在沒事了。它應該是MenuException,這就是爲什麼我每次都得到錯誤。非常感謝你的幫助 – 2014-10-12 11:13:28

2

throws menuException應該是...

  1. Decleared方法簽名的一部分,
  2. 應該拋出一個實際Exception類(而不是已經存在的情況下)...

例如...

public String displayMenu() throws MenuException { 

    for(int x = 0; x < entreeChoice.length; ++x){ 
     menu = menu + "\n" + (x+1) + "for" + entreeChoice[x]; 
     initial[x] = entreeChoice[x].charAt(0); 
    } 
    //throws menuException 


    String input = JOptionPane.showInputDialog(null, "Type your selection, then press Enter." + menu); 
    choice = Integer.parseInt(input); 
    return (entreeChoice[choice - 1]); 
} 

您可能希望通過Code Conventions for the Java TM Programming Language進行閱讀,這將使人們更容易閱讀您的代碼並讓您閱讀其他人