是否可以执行此代码尝试执行的操作(当前代码格式导致错误)
public String fileStream(){
Object[] yesNo = {"Yes",
"No",};
int nn = JOptionPane.showOptionDialog(null,"Would you like to use previously entered data?","Welcome Back?",JOptionPane.YES_NO_OPTION,JOptionPane.QUESTION_MESSAGE, null, yesNo,yesNo[1]);
if (nn == 0){
String savedBallNumber = readFromFile();
return savedBallNumber;
}
if (nn == 1){
String ballNumber = JOptionPane.showInputDialog("Please enter the number of balls you want on the screen:");
return ballNumber;
}
}
当我将鼠标悬停在fileStream上时出现的错误是“此方法必须返回String类型的结果”
答案 0 :(得分:4)
你的问题是你的代码在两个if块中返回,但没有其他阻塞意味着你有可能在不返回任何内容的情况下结束该方法:
例如:
public String someMethod {
if (a) {
return "foo";
}
if (b) {
return "bar";
}
}
如果a和b都不成立,它会返回什么。
解决方案:将最后一个if块更改为else块:
public String fileStream() {
Object[] yesNo = { "Yes", "No"};
int nn = JOptionPane.showOptionDialog(null,
"Would you like to use previously entered data?", "Welcome Back?",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null,
yesNo, yesNo[1]);
if (nn == 0) {
String savedBallNumber = readFromFile();
return savedBallNumber;
} else {
String ballNumber = JOptionPane.showInputDialog("Please enter the number of balls you want on the screen:");
return ballNumber;
}
}