簡體   English   中英

我試圖通過for循環調用一個方法,第一次迭代只會讀取方法中的第一行代碼

[英]I'm trying to call a method through a for loop, and the first iteration will only read the first line of code in the method

我正在嘗試使用增強的 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);
}

而這里是output(數據質量較差,僅作為示例):

賬戶類型是什么? (個人/家庭)

個人

輸入您的卡號:

1234123412341234

輸入有效期:

02/24

下一個用戶的email是什么?

abc@def.com

賬戶類型是什么? (個人/家庭)

家庭

輸入您的卡號:

1234123412341234

輸入有效期:

02/24

有多少用戶?

3

下一個用戶的email是什么? 下一個用戶的email是什么?

abc@def.com

下一個用戶的email是什么?

abc@defg.com

賬戶類型是什么? (個人/家庭)

家庭

輸入您的卡號:

1234123412341234

輸入有效期:

02/24

有多少用戶?

2

下一個用戶的email是什么? 下一個用戶的email是什么?

xyz@abc.com

有誰知道如何解決這一問題?

Scanner.nextInt不會消耗您在 nummers 之后輸入的換行符。 因此,之后的任何 readline 都會消耗換行符 - 並停止,因為它就是這樣做的。

正因為如此,輸入用戶數后的第一個 email 提示總是會返回一個空字符串。 您可以在 output 中看到這一點:這是 email 提示重復的情況。

要解決此問題,請在所有keyboard.nextInt()調用之后調用keyboard.nextLine() ()(並忽略該函數的 output)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM