Java幸运转盘游戏代码报错:Cannot resolve symbol 'wheel'求助
解决「Cannot resolve symbol 'wheel'」错误及代码修正
错误原因
wheel是你在func1方法内部定义的局部变量,局部变量只能在它被定义的方法内部使用,main方法根本访问不到这个变量,所以IDEA提示找不到该符号。
修正方案
这里提供两种新手友好的解决方式:
方式1:让func1返回奖品列表
修改func1的返回值类型,把创建好的奖品列表返回给main方法,这样main里就能拿到wheel变量:
import java.util.*; public class Game { public static ArrayList<String> func1(String[] prizes) { ArrayList<String> wheel = new ArrayList<>(5); Collections.addAll(wheel, prizes); return wheel; // 返回初始化好的奖品列表 } public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random randomGenerator = new Random(); String[] prizes = {"Television", "iPhone", "Microwave", "Ventilator", "Gift Card"}; // 接收func1返回的列表,main方法现在能访问wheel了 ArrayList<String> wheel = func1(prizes); System.out.println("输入任意数字启动抽奖:"); int turn = scanner.nextInt(); // nextInt()不需要参数,你之前的写法有误 int tries = 0; while(tries < 3) { System.out.println("输入任意数字进行第" + (tries+1) + "次抽奖:"); turn = scanner.nextInt(); // 每次抽奖重新生成随机索引,避免三次抽到同一个奖品 int index = randomGenerator.nextInt(wheel.size()); // 注意a后面加空格,避免输出"You won aiPhone"这类奇怪内容 System.out.println("You won a " + wheel.get(index)); tries++; } scanner.close(); // 用完Scanner记得关闭资源 } }
方式2:直接在main方法里初始化奖品列表
如果func1只是用来初始化列表,完全可以把这部分逻辑直接放到main里,减少不必要的方法调用,更直观:
import java.util.*; public class Game { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Random randomGenerator = new Random(); String[] prizes = {"Television", "iPhone", "Microwave", "Ventilator", "Gift Card"}; // 直接在main里创建wheel变量,整个main方法都能访问 ArrayList<String> wheel = new ArrayList<>(5); Collections.addAll(wheel, prizes); System.out.println("输入任意数字启动抽奖:"); int turn = scanner.nextInt(); int tries = 0; while(tries < 3) { System.out.println("输入任意数字进行第" + (tries+1) + "次抽奖:"); turn = scanner.nextInt(); int index = randomGenerator.nextInt(wheel.size()); System.out.println("You won a " + wheel.get(index)); tries++; } scanner.close(); } }
额外修正的小细节
- 修正
scanner.nextInt(1)的错误用法:nextInt()方法没有参数,直接用scanner.nextInt()读取用户输入即可。 - 把随机索引生成移到循环内:原来的代码只在循环外生成一次索引,三次抽奖会得到同一个奖品,现在每次抽奖都生成新的随机索引。
- 补充输出字符串的空格:避免出现
You won aiPhone这类格式错误的输出。 - 添加Scanner关闭操作:使用完IO资源后及时关闭是良好的编程习惯。
内容的提问来源于stack exchange,提问作者Space.Llama
相关产品推荐
相关产品推荐

