简体   繁体   中英

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.

I have trouble in outputting a false found boolean, which would allow to me print that the given name was not 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 ). 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 . 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.");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM