0

I have got Bank class, Consumer class and consumer.txt with data of consumers. There is a simple method in Bank class to do consumer service.

 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));
                }
            }
        }
    }
}

When the i in for loop is greater than 0, the accNum = sc.nextLine() does not get data i enter while customers[i].accountNumber shows correct data. The accNum is just empty, but for i = 0 it works fine.

txt file is "name" "surname" balance "account number"

JAN KOWALSKI 20000 012345678912
ANNA GRODZKA 35000 987654321098
KUBA NOWAK 15000 789456123078
TYMOTEUSZ KOLARZ 18000 654987321078
viverte
  • 33
  • 7

1 Answers1

0

Instead of using accNum = sc.nextLine(); I suggest you to use accNum = sc.next(); since your accNum does not contain any spaces.

since you use int choice = sc.nextInt(); , nextInt() is not read new line character but you create new line by hitting Enter. Therefore accNum = sc.nextLine(); reads that new line character and returns.

Dinithi
  • 28
  • 4