以下代码仅检查ArrayList中的第一项。当我输入ArrayList中但不在第一个位置的项目时,我收到“请输入有效名称”的错误消息。
我怎样才能解决这个问题?谢谢!
这是我的代码:
private ArrayList<Account> accounts = new ArrayList<>();
for(Account a : accounts)
{
while(true)
{
System.out.printf("Customer name: ");
String customerName = scanner.next();
if(customerName.equals(a.getName()))
{
System.out.println("You entered " + a.getName());
break;
}
else
{
System.out.println("Please enter a valid name");
}
}
}
你必须打破。当您在列表上进行迭代时,您必须考虑逻辑。它可以像这个代码;
ArrayList<Account> accounts = new ArrayList<>();
boolean isMatched = false;
while (true) {
for (Account account : accounts) {
System.out.printf("Customer name: ");
String customerName = scanner.next();
if (customerName.equals(account.getName())) {
isMatched = true;
break;
}
}
if (isMatched) {
System.out.println("You entered " + account.getName());
break;
}
System.out.println("Please enter a valid name");
}
PS:boolean
值,当找到客户名称结束while循环时。
内循环确实这样做:
while(true) {
这里没有用处。它只是在外循环中循环,因此总是与相同的a
帐户进行比较!
基本上你必须交换两个循环!
问题是无限循环。
while(true)
这个循环仅在customerName == firstElement.Name
时断开,否则它是一个无限循环。相反,我认为你想要尝试的是在for循环之外移动while循环。所以代码看起来像这样。
private ArrayList<Account> accounts = new ArrayList<>();
while(true)
{
System.out.printf("Customer name: ");
String customerName = scanner.next();
for(Account a : accounts){
if(customerName.equals(a.getName())){
System.out.println("You entered " + a.getName());
break;
}else{
System.out.println("Please enter a valid name");
}
}
}
你遇到的问题是因为你只是一直在检查第一个元素。在您输入第一个元素之后(并在(1)中打破循环),您将转到第二个元素。
想象一下,你的arrayList中有
"hello", "bye"
你将进入你的循环,直到发短信第一个元素(“你好”)。
解:
while(true)
{
System.out.printf("Customer name: ");
String customerName = scanner.next();
if (accounts.contains(customerName)){
System.out.println("You entered " + customerName);
break;
}
else{
System.out.println("Please enter a valid name");
}
}