[英]Eclipse dead code warning, but what is wrong?
我已經編寫了一種方法來檢查我的字符串是否在文件中,但是eclipse會給出無效代碼警告。 這是我的方法:
private boolean KeyPresent(String key){
try{
BufferedReader fileReader=new BufferedReader(new FileReader(keyPath));
while(true){
String s=fileReader.readLine();
if(s.equals(key)){
fileReader.close();
return true;
}else if(s==null){
fileReader.close();
return false;
}
}
}catch(IOException e){
e.getStackTrace()
return false;
}
}
else if(s==null)
部分是警告的來源。 為什么? 如果找不到任何匹配的結果(並且即將輸出均為null),則return false
。 我認為還可以。 怎么了?
還有一個問題。 哪個更好用?
String s;
while(true){
s="New Value";
....
}
要么
while(true){
String s="new value";
...
}
我認為垃圾收集器會消耗系統資源,因此第一個更好。 但是,我在第二個例子中看到了更多示例。 您會使用哪一個?
查看整個if / else:
if (s.equals(key)) {
...
} else if (s == null) {
...
}
如果s
為 null,則s.equals(key)
將引發NullPointerException
因此,您永遠不會進入第二個if
塊。
無論如何,您都應該使用try-with-resources塊,就我個人而言,我也不會捕獲IOException
……只要讓它冒泡:
private boolean keyPresent(String key) throws IOException {
try (BufferedReader reader = new BufferedReader(new FileReader(keyPath))) {
String line;
while ((line = reader.readLine()) != null) {
if (line.equals(key)) {
return true;
}
}
return false;
}
}
注意這里沒有垃圾收集差異。 在循環之前聲明變量僅意味着您可以在while條件內分配值。
如果s
為null,則將執行第一個if
並將拋出NullPointerException。 您的else if
無法執行。 您必須切換if
和else if
才能正確處理空指針。
回答很簡單:如果s將為null,則在此行
s.equals(key)
NullPointerException將被拋出,並且programm將永遠不會豐富此內容
else if (s == null)
條件。 僅當s!= null時,programm才會豐富此條件。 因此,這種情況總是錯誤的 。 您最好用以下方式重寫此代碼段:
while (true) {
String s = fileReader.readLine();
if (s == null) {
fileReader.close();
return false;
} else if (s.equals(key)) {
fileReader.close();
return true;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.