即使在if-else语句之后,布尔变量也设置为true

时间:2016-05-02 16:51:38

标签: java if-statement boolean

我正在为学校编写一个程序,以便从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();
    }
}

2 个答案:

答案 0 :(得分:3)

if(found = false){ false分配给found,然后测试结果(始终为false)。等于运算符是==,而不是==始终是分配

但是对于布尔变量,您基本上不需要==!=。只需测试变量本身:

if (!found) {

答案 1 :(得分:2)

请检查您的上一次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.");
}