修改java代码错误
问题描述:
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代码错误
答
取决于你想要做什么(抛出一个异常,或宣布你的方法可能会抛出这种类型的异常):
要么改变它太:
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();
...
}
答
throws menuException
应该是...
- Decleared方法签名的一部分,
- 应该抛出一个实际
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进行阅读,这将使人们更容易阅读您的代码并让您阅读其他人
@Dan想想吧,后者将不起作用,因为'throw new ...'后面的代码将变得无法访问。编辑答案。 – Eran 2014-10-12 11:08:14
现在没事了。它应该是MenuException,这就是为什么我每次都得到错误。非常感谢你的帮助 – 2014-10-12 11:13:28