java - sc.nextLine() 不读取行
问题描述
我有Bank
班级,Consumer
班级和consumer.txt
消费者的数据。类中有一个简单的方法Bank
来做消费者服务。
public static void bankService(String file) {
String[][] customersString = readFileToString(file);
customers = readFile(file);
Scanner sc = new Scanner(System.in);
double cash;
String accNum;
for (int i = 0; i < customers.length; i++) {
customers[i].name = customersString[i][0];
customers[i].surname = customersString[i][1];
customers[i].balance = Integer.parseInt(customersString[i][2]);
customers[i].accountNumber = customersString[i][3];
System.out.println("Enter your account number: ");
accNum = sc.nextLine();
if (accNum.equals(customers[i].accountNumber)) {
System.out.println("Your balance is: " + customers[i].balance);
System.out.println("If you want to deposit cash press '1', if you want to withdraw cash press '2'");
int choice = sc.nextInt();
switch (choice) {
case 1 -> {
cash = sc.nextDouble();
System.out.println(customers[i].name + " " + customers[i].surname +
" " + customers[i].cashDeposit(cash));
}
case 2 -> {
cash = sc.nextDouble();
System.out.println(customers[i].name + " " + customers[i].surname +
" " + customers[i].cashWithdraw(cash));
}
}
}
}
}
当 for 循环中的 i 大于 0 时,accNum = sc.nextLine()
不获取我输入的数据,而customers[i].accountNumber
显示正确的数据。accNum 只是空的,但i = 0
它工作正常。
txt 文件为“姓名”“姓氏”余额“帐号”
JAN KOWALSKI 20000 012345678912
ANNA GRODZKA 35000 987654321098
KUBA NOWAK 15000 789456123078
TYMOTEUSZ KOLARZ 18000 654987321078
解决方案
而不是使用 accNum = sc.nextLine(); 我建议你使用 accNum = sc.next(); 因为您的 accNum 不包含任何空格。
因为你使用 int choice = sc.nextInt(); , nextInt() 不是读取换行符,而是通过按 Enter 创建新行。因此 accNum = sc.nextLine(); 读取该换行符并返回。
推荐阅读
- javascript - Ionic 应用程序中全屏模式下的视频问题
- python - 替换为发生的概率
- android - 如何通过 UI 测试读取 Jetpack Compose TextField 的语义值?
- vba - Excel VBA到Word,查找和替换第二个实例
- python - 从 Python 中查询 JSON 类型的 SQL 表列需要很长时间?
- r - 在字符串的一部分周围插入字符?
- python - 如何将 python 中的 3d 图的顶点与 matplotlib 连接?
- azure - Azure devops 管道自托管 Kubernetes 集群身份验证问题
- python - 如何反向补充具有多个序列的 excel 文件?
- c - 为什么在 C 中解析 csv 文件时,大小与 prev_size 相比损坏?