始终返回false

时间:2014-03-01 19:13:29

标签: java methods output

我被要求做一个程序,我检查用户输入的名字是否在我在计算机上创建的文件中。我编写了代码并且它没有显示任何编译错误,但是当它运行时,布尔表达式始终为false。请帮我解决这个问题。男孩名字文件上的样本名称是Martin,女孩名字是Emily。

import java.util.*;
import java.io.*;
public class nameSearch1
{
    public boolean readingGirlNames () throws IOException
    {
        String[] girlNames = new String [200];
        int i = 0;
        File file = new File ("GirlNames.txt");
        Scanner inputFile = new Scanner(file);

        while(inputFile.hasNext() && i < girlNames.length )
        {
            girlNames [i] = inputFile.nextLine();
            i++;
        }
        inputFile.close();

        Scanner keyboard=new Scanner(System.in);
        boolean girlName = false ;
        nameSearch object4 = new nameSearch();
        System.out.println(" Enter the Girl Name you wish to see : ");

        String nameCheckGirl = keyboard.nextLine();

        for ( int index = 0 ; index < 200 ; index ++ )
        {
            if( nameCheckGirl == girlNames[index])
            { 
                girlName = true;
            }

        }
        return girlName;
    }

    public boolean readingBoyNames () throws IOException
    {
        String[] boyNames = new String [200];
        int i = 0;
        File file = new File ("BoyNames.txt");
        Scanner inputFile = new Scanner(file);

        while(inputFile.hasNext() && i < boyNames.length )
        {
            boyNames [i] = inputFile.nextLine();
            i++;

        }
        inputFile.close();




        nameSearch object2 = new nameSearch ();
        Scanner keyboard=new Scanner(System.in);
        boolean boyName = false ;

        System.out.println(" Enter the Boy Name you wish to see : ");

        String nameCheckBoy = keyboard.nextLine();

        for ( int index = 0 ; index < 200 ; index ++ )
        {
            if( nameCheckBoy == boyNames[index])
            { 
                boyName = true;
            }

        }
        return boyName;
    }

    public static void main(String[]Args)
    {
        Scanner keyboard = new Scanner(System.in);

        nameSearch1 object1 = new nameSearch1 ();

        try
        {
            System.out.println(" The search result for the Girl's name is : " + object1.readingGirlNames ());
        }
        catch (IOException ioe)
        {
            System.out.println(" Exception!!! ");

            ioe.printStackTrace();
        }

        try
        {
            System.out.println(" The search result for the Boy's name is : " + object1.readingBoyNames ());
        }
        catch (IOException ioe)
        {
            System.out.println(" Exception!!! ");

            ioe.printStackTrace();
        }

    }
}

1 个答案:

答案 0 :(得分:1)

为什么要将带有==运算符更改的字符串与equals()

进行比较
if( nameCheckBoy.equals(boyNames[index]))
            { 
                boyName = true;
            }