gpt4 book ai didi

java - 总是返回 false

转载 作者:行者123 更新时间:2023-12-01 13:20:00 25 4
gpt4 key购买 nike

我被要求执行一个程序,在其中检查用户输入的名称是否在我在计算机上创建的文件中。我编写了代码,它没有显示任何编译错误,但是当它运行时, boolean 表达式始终为 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();
}

}
}

最佳答案

为什么要将字符串与 == 运算符更改与 equals() 进行比较

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

关于java - 总是返回 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22119046/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com