亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

由于 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條經驗 獲得超7個贊

在函數調用中使用輸入變量之前,請嘗試減慢程序速度以接受輸入。

也就是說:驗證“選擇”不具有任何無意義的價值。

那應該有幫助。


查看完整回答
反對 回復 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 關注
  • 293 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號