我试图通过 for 循环调用一个方法,第一次迭代只会读取方法中的第一行代码

问题描述

我正在尝试使用增强的 for 循环来连续多次调用一个方法,但是如果我迭代不止一次,第一次迭代只会读取第一行代码。以下是我正在使用的两种方法

public Account() {

    this.subDetails = new HashMap<Integer,String>();
    
    System.out.println("What is the account type? (Individual/Family)");
    String planType = keyboard.nextLine();
    
    System.out.println("Enter your card number: ");
    this.cardNum = keyboard.nextLine();
    
    System.out.println("Enter the expiration date: ");
    this.cardExp = keyboard.nextLine();
    
    if (planType.equals("Family")) {
        System.out.println("How many users?");
        int numUsers = keyboard.nextInt();
        for (int z=0; z<numUsers; z++) {
            this.addUser();
        }
        StreamingService.numFamUsers = StreamingService.numFamUsers + numUsers;
        StreamingService.monthlyRevenue = StreamingService.monthlyRevenue + 14.99;
        StreamingService.monthlyFamRevenue = StreamingService.monthlyFamRevenue + 14.99;
    }
    else if (planType.equals("Individual")) {
        this.addUser();
        StreamingService.numIndUsers++;
        StreamingService.monthlyRevenue = StreamingService.monthlyRevenue + 9.99;
        StreamingService.monthlyIndRevenue = StreamingService.monthlyIndRevenue + 9.99;
    }
    StreamingService.numAccounts++;
    this.subDetails.put(i,planType);
    i++;

}


public void addUser() {
        System.out.println("What is the email of the next user?");
        String e = keyboard.nextLine();
        User y = new User(e,i);
        StreamingService.userEmails.add(y);
        StreamingService.numUsers++;
        this.acctUsers.add(e);
}

这是输出(数据质量很差,仅用作示例):

账户类型是什么? (个人/家庭)

个人

输入您的卡号:

1234123412341234

输入到期日期:

02/24

一个用户的电子邮件是什么?

abc@def.com

账户类型是什么? (个人/家庭)

家庭

输入您的卡号:

1234123412341234

输入到期日期:

02/24

有多少用户

3

一个用户的电子邮件是什么?下一个邮箱是什么 用户

abc@def.com

一个用户的电子邮件是什么?

abc@defg.com

账户类型是什么? (个人/家庭)

家庭

输入您的卡号:

1234123412341234

输入到期日期:

02/24

有多少用户

2

一个用户的电子邮件是什么?下一个邮箱是什么 用户

xyz@abc.com

有人知道如何解决这个问题吗?

解决方法

Scanner.nextInt 不会消耗您在数字后面输入的换行符。因此,之后的任何 readline 都会消耗换行符 - 并停止,因为它就是这样做的。

因此,输入用户数后的第一封电子邮件提示将始终返回空字符串。您可以在输出中看到这一点:这是电子邮件提示重复的情况。

要解决此问题,请在所有 keyboard.nextLine() 调用之后调用 keyboard.nextInt()(并忽略该函数的输出)。