gpt4 book ai didi

java - 返回 2 个不同的字符串

转载 作者:行者123 更新时间:2023-11-29 03:25:38 27 4
gpt4 key购买 nike

是否可以执行此代码尝试执行的操作(当前代码格式导致错误)

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 上时出现的错误是“此方法必须返回字符串类型的结果”

最佳答案

您的问题是您的代码在两个 if block 中返回,但没有 else block ,这意味着该方法有可能在不返回任何内容的情况下结束:

例如:

public String someMethod {
if (a) {
return "foo";
}
if (b) {
return "bar";
}
}

如果 a 和 b 都不为真,它返回什么。

解决方案:将最后一个 if block 更改为 else block :

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;
}
}

关于java - 返回 2 个不同的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21213241/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com