【问题标题】:Boolean variable set to true even after if-else statement即使在 if-else 语句之后,布尔变量也设置为 true
【发布时间】:2016-05-02 16:51:38
【问题描述】:

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

【问题讨论】:

  • 即使在那之后,逻辑也存在严重缺陷。您对 found 值的检查只检查最后一个输入行 - 它的值对于所有其他输入行都会被忽略。
  • 熟悉您的 IDE 的调试器应该会有很大帮助。你会看到found 每次都变成false ;)

标签: java if-statement boolean


【解决方案1】:

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

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

if (!found) {

【讨论】:

    【解决方案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.");
    }
    

    【讨论】:

    • 这就是你永远不应该将布尔值与真或假进行比较的原因。
    • 所以考虑做 if(!found)。
    猜你喜欢
    • 1970-01-01
    • 2020-09-06
    • 2013-03-13
    • 2021-09-14
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多