首页 > 解决方案 > 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

标签: java

解决方案


而不是使用 accNum = sc.nextLine(); 我建议你使用 accNum = sc.next(); 因为您的 accNum 不包含任何空格。

因为你使用 int choice = sc.nextInt(); , nextInt() 不是读取换行符,而是通过按 Enter 创建新行。因此 accNum = sc.nextLine(); 读取该换行符并返回。


推荐阅读