如何解决我试图通过 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()
(并忽略该函数的输出)。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。