Java中choiceList方法返回值无法在main方法中使用的问题
问题解决:正确获取Java方法返回值
问题根源
- 调用
choiceList()方法时未接收它返回的int值,switch语句里的choice是未声明的局部变量,因此IDE提示"cannot find symbol" - Java不允许在方法内部嵌套定义另一个方法,你尝试在main里定义choiceList的做法本身不合法,再加上main是void类型,自然会报"void cannot return"错误
正确修改方式
在main方法中调用choiceList()时,将返回值赋值给一个int类型变量,后续就能在switch里正常使用该变量:
import java.util.Scanner; public class YourClass { // 补充你的类名 public static void main(String[] args) { // 接收方法返回值,赋值给choice变量 int choice = choiceList(); switch (choice) { case 1: // 执行对应逻辑 break; case 2: // 执行对应逻辑 break; case 0: break; } } public static int choiceList() { Scanner jauns = new Scanner(System.in); System.out.println("1. Show the seats"); System.out.println("2. Buy a ticket"); System.out.println("0. Exit"); int choice = jauns.nextInt(); jauns.close(); // 关闭Scanner释放资源 return choice; } }
额外优化提示
可以使用try-with-resources语法自动关闭Scanner,避免手动关闭遗漏的问题:
public static int choiceList() { try (Scanner jauns = new Scanner(System.in)) { System.out.println("1. Show the seats"); System.out.println("2. Buy a ticket"); System.out.println("0. Exit"); return jauns.nextInt(); } // try块结束后自动关闭Scanner }
内容的提问来源于stack exchange,提问作者Edgar
相关产品推荐
相关产品推荐

