[英]Problem matching Java String against array
我需要查看字符串值是否與對象值匹配,但是為什么這樣不起作用?
public int countPacks(String flavour) {
int counter = 0;
for(int index = 0; index < packets.size(); index++) {
if (packets.equals(flavour)) {
counter ++;
}
else {
System.out.println("You have not entered a correct flavour");
}
}
return counter;
}
什么是“數據包”? 它不會是字符串-那么它將如何等於字符串?
我懷疑您的意思是:
if (packets.get(index).equals(flavour))
但是,即使每個包裝都有“錯誤”口味,您仍然要為每個“錯誤”口味打印“您沒有輸入正確的口味”!
我懷疑您想將錯誤報告移至循環結束后的方法末尾,並且僅在counter == 0
執行
你可能會說類似
if (packets.get(index).equals(flavour)) {
...
假設數據包是一個Collection(並且您使用的是JDK 1.5或更高版本),則還可以執行以下方法:
public int countPacks(String flavor) {
int numOccurrences = java.util.Collections.frequency(packets, flavor);
if(numOccurrences == 0) {
System.out.println("You have not entered a correct flavor");
}
return numOccurrences;
}
在Object中聲明的方法的問題在於,在使用它們時缺少靜態類型檢查。 同步也是如此,在這種情況下,鎖定錯誤的對象很常見。
在這種情況下,Object.equals(Object)可與任何兩個對象一起使用。 您已經使用了集合,數據包,而不是從中獲取元素。 重要的問題不是該特定錯誤是如何產生的,而是我們如何首先防止它發生。
首先,使用泛型並將獲取的每個元素分配給靜態類型的局部變量:
public int countPacks(String flavour) {
// [ The field represents a count. ]
int count = 0;
for(int index=0; index<packets.size(); ++index) {
String packet = packets.get(index);
if (packet.equals(flavour)) {
++count;
}
}
// [The error mesage was printed for each non-match.
// Even this is probably wrong,
// as it should be valid to have no packs of a valid flavour.
// Having the message in this method is actually a bit confused.]
if (count == 0) {
System.out.println("You have not entered a correct flavour");
}
return count;
}
我們可以使用增強的for循環來進一步整理。
public int countPacks(String flavour) {
int count = 0;
for(String packet : packets) {
if (packet.equals(flavour)) {
++count;
}
}
if (count == 0) {
System.out.println("You have not entered a correct flavour");
}
return count;
}
這看起來更清楚,但是一個好的程序員知道他/她的庫。
public int countPacks(String flavour) {
int count = Collections.frequency(packets, flavour);
if (count == 0) {
System.out.println("You have not entered a correct flavour");
}
return count;
}
您可能還考慮了Map<String,Integer>
而不是集合。
您應該以這種方式做到這一點,以確保您確實以最簡單的方式比較字符串。
我也修復了你的循環
public int countPacks(String flavour, List packets)
{
int counter = 0;
for (Iterator iter = packets.iterator(); iter.hasNext();) {
Map packet = (Map) iter.next();
if (packet.get("flavour").toString().equalsIgnoreCase(flavour)) {
counter ++;
}
else {
System.out.println("You have not entered a correct flavour");
}
}
return counter;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.