Java程序运行抛出NoSuchElementException错误求助
NoSuchElementException in Your Java Banking Program Hey Jeff, let's break down why you're hitting that java.util.NoSuchElementException and get your code working smoothly again.
What's Causing the Error?
The biggest issue here is using two separate Scanner objects (in and strng) to read from the same input stream (System.in). When multiple Scanners access System.in, they interfere with each other—one might consume input that the other is waiting for, leading to the exception when a Scanner tries to read data that no longer exists.
Additionally, there's a small input handling quirk with nextInt(): it reads the integer but leaves the newline character in the input stream. If you call nextLine() right after, it'll just read that empty newline instead of the actual input you want.
Step-by-Step Fixes
- Get rid of the second Scanner: Use only one
Scanner infor all input operations to avoid stream conflicts. - Clean up newline characters after
nextInt(): Addin.nextLine()after everynextInt()call to consume the leftover newline, so subsequentnextLine()reads work as expected. - Fix withdrawal re-input logic: The original code asks for a valid amount once but doesn't re-check—we'll add a loop to keep prompting until a valid amount is entered.
Corrected Full Code
import java.util.*; class Account { String name, acc_type; int Acc_num, Acc_Balance; Account() { } Account(String n, int acc_num, int b, String a_t) { name = n; Acc_num = acc_num; Acc_Balance = b; acc_type = a_t; } } // end class class create_account extends Account { create_account(String n, int acc_num, int b, String a_t) { name = n; Acc_num = acc_num; Acc_Balance = b; acc_type = a_t; } create_account() { super(); } void insert(String n, int acc_num, String a_t) { name = n; acc_type = a_t; Acc_num = acc_num; Acc_Balance = 0; } void display_details() { System.out.println("Depositor Name :" + name); System.out.println("Account Number : " + Acc_num); System.out.println("Account Balance : " + Acc_Balance); System.out.println("Account Type : " + acc_type); } void deposite(int acc_num, int money) { Acc_Balance = money; } int withdraw(int withd) { Acc_Balance = Acc_Balance - withd; return Acc_Balance; } } // end class public class Main { public static void main(String args[]) { String user_name = null, type; type = null; int balance = 0, tmp = 0; int withd = 0, cb = 0; // Generate Random Account Number int aNumber = (int) ((Math.random() * 9000) + 1000); create_account user = new create_account("user", 0, 0, "savings"); // Use only ONE Scanner for all input Scanner in = new Scanner(System.in); int userChoice; boolean quit = false; do { System.out.println("1. Create Account"); System.out.println("2. Deposit money"); System.out.println("3. Withdraw money"); System.out.println("4. Check balance"); System.out.println("5. Display Account Details"); System.out.println("0. to quit: \n"); System.out.print("Enter Your Choice : "); userChoice = in.nextInt(); // Consume the newline after nextInt() to avoid empty nextLine() reads in.nextLine(); switch (userChoice) { case 1: System.out.print("Enter your Name : "); user_name = in.nextLine(); System.out.print("Enter Account Type : "); type = in.nextLine(); // Allow account types with spaces user.insert(user_name, aNumber, type); System.out.println("\n\tYour Account Details\n\tDon't Forget Account Number\n"); System.out.println("**************************"); user.display_details(); break; case 2: System.out.print("Enter your account Number : "); tmp = in.nextInt(); in.nextLine(); // Consume newline if (tmp == user.Acc_num) { System.out.print("Enter Amount Of Money : "); balance = in.nextInt(); in.nextLine(); // Consume newline user.Acc_Balance = balance; System.out.println("\t Successfully Deposited."); } else { System.out.println("Wrong Account Number."); } break; case 3: System.out.print("Enter your account Number : "); tmp = in.nextInt(); in.nextLine(); // Consume newline if (tmp == user.Acc_num) { if (user.Acc_Balance == 0) { System.out.println("Your Account is Empty."); } else { // Loop until valid withdrawal amount is entered do { System.out.print("Enter Amount Of Money : "); withd = in.nextInt(); in.nextLine(); // Consume newline if (withd > user.Acc_Balance) { System.out.println("Error: Amount exceeds current balance. Please enter a valid amount."); } } while (withd > user.Acc_Balance); cb = user.withdraw(withd); System.out.println("Your Current Balance : " + cb); } } else { System.out.println("Wrong Account Number."); } break; case 4: System.out.print("Enter your Account Number : "); tmp = in.nextInt(); in.nextLine(); // Consume newline if (tmp == user.Acc_num) { System.out.println("Your Current Balance : " + user.Acc_Balance); } else { System.out.println("Wrong Account Number."); } break; case 5: System.out.print("Enter your Account Number :"); tmp = in.nextInt(); in.nextLine(); // Consume newline if (tmp == user.Acc_num) { user.display_details(); } else { System.out.println("Wrong Account Number."); } break; case 0: quit = true; break; default: System.out.println("Wrong Choice."); break; } System.out.println("\n"); } while (!quit); System.out.println("Thanks !"); in.close(); // Clean up the scanner when done } // end main function } // end main class
Key Changes Explained
- Single Scanner: Removed the redundant
strngScanner to eliminate input stream conflicts. - Newline Handling: Added
in.nextLine()after everynextInt()to clear leftover newlines, ensuringnextLine()reads actual user input instead of empty strings. - Robust Withdrawal Logic: Added a
do-whileloop to keep prompting for a valid withdrawal amount until the user enters one that doesn't exceed their balance. - Flexible Account Type Input: Switched from
in.next()toin.nextLine()for account type, allowing users to enter types with spaces (like "fixed deposit") if needed.
Give this code a run—this should resolve the NoSuchElementException and make your banking program work as expected!
内容的提问来源于stack exchange,提问作者Jeff

