我的文字文件包括: 汤姆,结婚,埃里克,乐,凯文,本,萨利
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner (new FileReader("name.txt"));
String Name;
Scanner in = new Scanner(System.in);
System.out.println("Enter a name:");
Name= in.nextLine();
String name = null;
while(sc.hasNext())
{
int i=0;
name= sc.next();
String [] Str=name.split(",");
if (Name.equals(Str[i]))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
if (i<Str.length)
{
i++;
}
}
我想输入一个名字,然后在文本文件中显示。我尝试了很多方法,但仍然无法工作,请帮助我。
答案 0 :(得分:0)
您的代码只会检查Tom
数组中的第一个单词String
。如果要检查数组的每个单词,请使用for
循环。如果您输入Marry
,则会与Tom
进行比较,因此请回答No
。
while(sc.hasNext())
{
name= sc.next();
String [] Str=name.split(",");
for(String s: Str){
if (Name.equals(s))
{
System.out.println("Yes");
}
else
{
System.out.println("No");
}
}//for missed. otherwise it will check only the first word in the String array
}
修改强> 还有一种检查方法
while(sc.hasNext())
{
name= sc.next(); //get each line from text file
String [] Str=name.split(",");
if(Arrays.asList(Str).contains(Name))//check whether Name contains or not
System.out.println("Yes");//If array contains the given input then Yes
else
System.out.println("No");//Otherwise No
}
答案 1 :(得分:0)
试试这个,它有效
public static void main(String[] args) throws IOException
{
Scanner sc = new Scanner (new FileReader("name.txt"));
String Name;
Scanner in = new Scanner(System.in);
System.out.println("Enter a name:");
Name= in.nextLine();
String name = null;
name= sc.next();
String [] Str=name.split(",");
int flag=0;
for(String sd:Str)
{
if (Name.equals(sd))
{
flag=1;
break;
}
else
{
continue;
}
}
if(flag==1)
System.out.println("yes");
else
System.out.println("no");
}
}