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
}
}
你为什么认为返回一些东西能解决你的问题?问问自己:你想做什么?你想随机选择一个数组中的元素。所以寻找那个。 – Tunaki