[英]Boolean variable set to true even after if-else statement
我正在編寫一個供學校使用的程序,以從SSA讀取一個嬰兒名字文件,並返回給定年份的名字數目統計信息。
我在輸出錯誤的found
布爾值時遇到麻煩,這將允許我打印未找到給定名稱的情況。
import java.util.*;
import java.io.*;
public class BabyNames{
public static void main(String []args)
throws FileNotFoundException
{
File file = new File ("babynames.txt");
Scanner input = new Scanner(file);
Scanner console = new Scanner(System.in);
int amount = 0;
System.out.print("Name? ");
String s1 = console.next();
boolean found = true;
while (input.hasNextLine()) {
String line = input.nextLine();
Scanner lineScan = new Scanner(line);
String name = lineScan.next();
if(name.equals(s1)){
found = true;
for(int i = 1; i<= 11; i++) {
amount = lineScan.nextInt();
int k = amount / 20;
System.out.print((i * 10) + 1890 + ": ");
for(int r = 1; r <= k; r++) {
System.out.print("*");
}
System.out.println();
}
} else {
found = false;
}
}
if(found = false){ //it never turns back into false
System.out.println(s1 + " is not found.");
}
input.close();
}
}
if(found = false){
將 false
分配給found
,然后測試結果(始終為false
)。 等於運算符是==
,不是=
。 =
總是賦值 。
但是對於布爾變量,您基本上從不需要==
或!=
。 只需測試變量本身:
if (!found) {
請檢查您的最后一個if
。 您可能是這個意思:
if(found == false){ //it never turns back into false
System.out.println(s1 + " is not found.");
}
但是為了防止將來出現這種錯誤,您應該這樣做:
if(!found){ //reads "if not found"
System.out.println(s1 + " is not found.");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.