Java Scanner.nextLine()跳过输入及next()输入全名报错问题求助
解决Scanner读取全名时的跳过/异常问题
嗨,我来帮你搞定这个输入全名的问题~ 你遇到的情况其实是Scanner的常见小坑,我给你拆解原因和解决方案:
问题根源
- 当你用
input.nextInt()读取用户选择的1/2时,它只会读取数字部分,不会处理数字后面的换行符。这时候紧接着调用input.nextLine(),它会直接读取这个残留的换行符,导致看起来“跳过了输入姓名的环节”。 - 如果你改用
input.next(),它是按空格分割输入的,所以输入全名(比如Zahraa Maher)时,它只会读取第一个词“Zahraa”,剩下的“Maher”会留在输入缓冲区里。后面调用input.nextInt()时,它会尝试把“Maher”当成整数解析,自然就抛出InputMismatchException了。
解决方案
只需要两步就能搞定:
- 在
input.nextInt()之后,额外调用一次input.nextLine(),把残留的换行符“吃掉”。 - 读取全名时继续用
input.nextLine(),这样就能完整获取带空格的姓名了。
修改后的驱动类代码
我把关键修改的地方用注释标出来了,还顺手修正了几个拼写和逻辑小问题:
package bankaccount; import java.util.Scanner; public class BankAccountTest { public static void main(String[] args) { Scanner input = new Scanner(System.in); int AccountMaking = 0; int operation=0; // 删掉了未使用的冗余变量newPalance System.out.println("Do you want to create an Account? \n if yes choose 1 \n if no choose 2"); AccountMaking=input.nextInt(); // 新增:吃掉nextInt()残留的换行符,避免后续nextLine()读取空内容 input.nextLine(); switch(AccountMaking){ case 1: BankAccount account1= new BankAccount(); System.out.println("Creating your account:"); System.out.println("Enter your name: "); // 用nextLine()读取全名,现在可以正常获取带空格的姓名了 account1.name=input.nextLine(); System.out.println("You have finished creating your account! \n Thank you. "); System.out.println("------------------------------------\n"); System.out.println("choose operation do you want to do: \n 1 Add new balance \n 2 withdraw balance" + " \n 3 show your balance\n 4 print your account info"); operation=input.nextInt(); switch (operation){ case 1: System.out.println("Enter the amount of balance you want to Add: "); account1.amount=input.nextDouble(); System.out.println(account1.deposit(account1.amount)); System.out.println("Your new balance has been added! \n Thank you. "); break; case 2: System.out.println("Enter the amount of balance you want to withdraw: "); account1.amount=input.nextDouble(); System.out.println(account1.withdraw(account1.amount)); System.out.println("Your new balance has been updated! \n Thank you. "); break; case 3: account1.BalancInquiry(); System.out.println("Your balance has been shown! \n Thank you. "); break; case 4: account1.PrintInfo(); break; default: System.out.println("We don't have this operation, please choose one of the options above! \n Thank you"); break; } break; // 新增break,避免执行完case1后跳到default逻辑 default: System.out.println("Thank you for using this application \n GoodBye! "); } } }
额外小修正
我还帮你调整了代码里的几个细节:
- 修正拼写错误:
Count→Account、palance→balance、createing→creating - 补充了case1后的break语句,避免逻辑串流
- 优化了部分提示语的通顺度
现在运行修改后的代码,就能正常输入全名啦~
内容的提问来源于stack exchange,提问作者Zahraa Maher
相关产品推荐
相关产品推荐

