[英]Comparing elements of ArrayList in loop gives unexpected result?
以下代碼僅檢查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");
}
}
}
內部循環可以做到這一點:
while(true) {
這里沒有目的。 它只是保持外循環內循環,因此總是針對同一個比較a
帳戶!
基本上,您必須交換兩個循環!
問題是無限的while循環。
while(true)
僅當customerName == firstElement.Name
,此循環才會customerName == firstElement.Name
,否則為無限循環。 相反,我認為您想嘗試的是將while循環移到for循環之外。 因此代碼看起來像這樣。
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");
}
}
}
你必須從中休息。 在列表上進行迭代時,您必須考慮邏輯。 它可以像這樣的代碼;
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(1)的循環),您將轉到第二個元素。
假設您的arrayList中有
"hello", "bye"
您將一直處於循環內,直到給第一個元素(“ hello”)發短信為止。
解:
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");
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.