为了账号安全,请及时绑定邮箱和手机立即绑定

由于 nextInt() 导致的 java.util.NoSuchElementException

由于 nextInt() 导致的 java.util.NoSuchElementException

守着一只汪 2023-09-27 21:21:37
我有 2 个类,即 MyClient 和 CustomerUserInterface。MyClient 类有一个 main 方法,我在其中调用 CustomerUserInterface 的方法。我的客户    public class MyClient {        public static void main(String args[]) {    CustomerUserInterface customerUserInterface = new CustomerUserInterfaceImpl();    Scanner scan = new Scanner(System.in);    customerUserInterface.registerLoginMenu();    int choice = scan.nextInt();    customerUserInterface.performOperationsOnRegisterLoginMenu(choice);        }    }客户用户界面public class CustomerUserInterfaceImpl implements CustomerUserInterface {private CustomerBL customerBl;private ProductInterface productInterface;public CustomerUserInterfaceImpl() {    customerBl = new CustomerBLImpl();    productInterface = new ProductInterfaceImpl();}@Overridepublic void registerLoginMenu() {    System.out.println("1. Register");    System.out.println("2. Login");    System.out.println("3. Exit");}@Overridepublic void register() {    Customer customer = CustomerInputHelper.inputCustomer();    boolean status=false;    try {        status = customerBl.registerUser(customer);    }catch (SQLException e) {        e.printStackTrace();    }    if(status) {        System.out.println("Register Success");        login();    }    else {        System.out.println("Register Unsuccessful");        registerLoginMenu();    }}我面临的问题是,在第一个 System.out 行之后,我在 login() 方法中遇到错误,即Exception in thread "main" java.util.NoSuchElementExceptionat java.util.Scanner.throwFor(Unknown Source)at java.util.Scanner.next(Unknown Source)at java.util.Scanner.nextInt(Unknown Source)at java.util.Scanner.nextInt(Unknown Source)注册成功后,寄存器会调用登录方法,但在登录方法调用之后,我收到上述错误。我不明白这个问题,因为用户注册了,但在调用登录方法后立即显示错误。
查看完整描述

3 回答

?
慕妹3146593

TA贡献1820条经验 获得超9个赞

您在 system.in 上注册 Scanner 两次,在 MyClient 中注册一次:


public class MyClient {

   public static void main(String args[]) {

     Scanner scan = new Scanner(System.in);

一旦进入 CustomerUserInterface 登录方法:


@Override

public void login() {

   Scanner scan = new Scanner(System.in);

这是行不通的,因为第一个扫描仪已经有了 System.in 流。


您需要在整个程序中使用相同的扫描仪实例。


查看完整回答
反对 回复 2023-09-27
?
qq_花开花谢_0

TA贡献1835条经验 获得超6个赞

在函数调用中使用输入变量之前,请尝试减慢程序速度以接受输入。

也就是说:验证“选择”不具有任何无意义的价值。

那应该有帮助。


查看完整回答
反对 回复 2023-09-27
?
长风秋雁

TA贡献1757条经验 获得超7个赞

该类的文档告诉您,如果输入流耗尽,则会抛出。因此我假设输入流由于某种原因关闭。ScannerNoSuchElementException


你如何运行你的代码?通过 IDE 还是仅通过java MyClient命令行调用?也许这就是你的错误。


如果您运行以下代码,它应该重复您的输入。如果这不起作用,那么您正在以错误的方式调用代码。


public class MyClient {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

        System.out.println(sc.nextInt());

    }

}


查看完整回答
反对 回复 2023-09-27
  • 3 回答
  • 0 关注
  • 108 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信