我是一名初学者程序员,并不完全理解方法及其工作原理。我正在尝试制作一个执行石头剪刀布的程序,该程序随机选择一个,然后要求用户输入。我遇到的问题是方法。我的代码如下,我得到的错误是我无法返回 void 方法的值,但我不知道我还能做些什么来使其工作。任何建议将不胜感激!
public class RPS {
public static void main (String[] args) {
String[] list = {"rock", "paper", "scissors"};
Random rand = new Random();
int x = rand.nextInt();
switch (x) {
case 0: return list[0];
case 1: return list[1];
case 2: return list[2];
}
最佳答案
return
用于从 return
所在的方法返回。
在这种情况下,我猜您想将所选值存储到某个位置,并稍后在相同的方法中使用它。
试试这个:
import java.util.Random;
public class RPS {
public static void main (String[] args) {
String[] list = {"rock", "paper", "scissors"};
Random rand = new Random();
int x = rand.nextInt();
String hand = null;
if (0 <= x && x <= 2) hand = list[x];
// do something using hand
System.out.println(hand);
}
}
这段代码可以消除错误,但是这段代码很有可能打印 null
,这不是一个好的代码。
如果你想使用return
,你可以把它放在另一个方法中。
import java.util.Random;
public class RPS {
public static void main (String[] args) {
String hand = selectHand();
// do something using hand
System.out.println(hand);
}
private static String selectHand() {
String[] list = {"rock", "paper", "scissors"};
Random rand = new Random();
int x = rand.nextInt();
switch (x) {
case 0: return list[0];
case 1: return list[1];
case 2: return list[2];
}
return null; // you must return something everytime from non-void method
}
}
关于java - 返回类型 void/方法替代方案?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36678911/