[英]Boolean variable set to true even after if-else statement
I am writing a program for school to read a file of baby names from the SSA and return statistics on the number of names for a given year. 我正在编写一个供学校使用的程序,以从SSA读取一个婴儿名字文件,并返回给定年份的名字数目统计信息。
I have trouble in outputting a false found
boolean, which would allow to me print that the given name was not found. 我在输出错误的
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){
assigns false
to found
and then tests the result (which will always be false
). if(found = false){
将 false
分配给found
,然后测试结果(始终为false
)。 The equality operator is ==
, not =
. 等于运算符是
==
,不是=
。 =
is always assignment . =
总是赋值 。
But with boolean variables, you basically never want ==
or !=
. 但是对于布尔变量,您基本上从不需要
==
或!=
。 Just test the variable itself: 只需测试变量本身:
if (!found) {
Please check your last if
. 请检查您的最后一个
if
。 You probably meant this: 您可能是这个意思:
if(found == false){ //it never turns back into false
System.out.println(s1 + " is not found.");
}
but to prevent this kind of mistake in the future, you should do this: 但是为了防止将来出现这种错误,您应该这样做:
if(!found){ //reads "if not found"
System.out.println(s1 + " is not found.");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.