[英]Boolean value assignment in Java
為總的問題提出的歉意,但是在以下方法中,for-each循環完成后,誰能解釋match
的值是什么?
嘗試進行編譯會產生警告: variable match might not have been initialised
。
public void listMatching(String searchString) {
boolean match;
for(String filename : files) {
if(filename.contains(searchString)) {
System.out.println(filename);
match = true;
}
else {
match = false;
}
}
if(match == false) {
System.out.println("No matches found for " + searchString);
}
}
首先,您需要定義boolean match = false;
另外,一旦找到匹配項,您就需要從循環中中斷,否則, match
狀態將被覆蓋。
if(filename.contains(searchString)) {
System.out.println(filename);
match = true;
break;
} // this wil help whether a match is found or not
如果您有興趣查找匹配數,則int counter = 0; if(filename.contains(searchString)){System.out.println(filename); match = true; 計數器++; } //這將有助於查找匹配數
最終System.out.println("number of matches for"+searchString+" : "+counter);
這是一個修復程序,它將執行您想要的操作:
public void listMatching(String searchString) {
boolean match = false; // initialize local variable
for(String filename : files) {
if(filename.contains(searchString)) {
System.out.println(filename);
match = true;
}
}
if(!match) { // same as 'match == false', just without comparison
System.out.println("No matches found for " + searchString);
}
}
局部變量必須初始化。 只有字段會獲得其類型的默認值。
如果在else
塊中將match
重新分配為false
,則即使在每個filename
包含searchString
(最后一個除外)的情況下,循環后也將為false
。
找到匹配項時,您需要打破循環。
您需要初始化找到的變量,也永遠無法運行循環,然后if條件將查看未初始化的變量,這就是編譯器要告訴您的內容
將變量初始化為false以避免在程序中發出警告。
另外, match
是一個變量,根據各種文件的內容(搜索相同的字符串),您要為同一變量分配true或false。
match
的最終布爾值只是在文件列表的最后一個文件中搜索字符串的結果。
它可能是文件數組為空,因此應為match變量設置默認值;
boolean match=false;
for(String filename : files) {
if(filename.contains(searchString)) {
System.out.println(filename);
match = true;
break;
}
}
如果您需要檢查所有文件是否都具有此搜索字符串U可以使用以下代碼:
boolean match=files.lenght!=0;
for(String filename : files) {
if(!filename.contains(searchString)) {
System.out.println(filename);
match = false;
break;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.