我目前在大学的入门级Java课程中,遇到了一些麻烦。上学期,我们从Python开始,我对它非常熟悉,我想说,我现在已经精通Python;然而Java是另一个故事。事情就不一样了。无论如何,这是我当前的任务:我需要编写一个类来搜索一个文本文档(作为参数传递),以查找用户输入的名称,并输出该名称是否在列表中。文本文档的第一行是列表中的名称数量。案文文件:
14
Christian
Vincent
Joseph
Usman
Andrew
James
Ali
Narain
Chengjun
Marvin
Frank
Jason
Reza
David我的密码是:
import java.util.*;
import java.io.*;
public class DbLookup{
public static void main(String[]args) throws IOException{
File inputDataFile = new File(args[0]);
Scanner stdin = new Scanner(System.in);
Scanner inFile = new Scanner(inputDataFile);
int length = inFile.nextInt();
String names[] = new String[length];
for(int i=0;i<length;i++){
names[i] = inFile.nextLine();
}
System.out.println("Please enter a name that you would like to search for: ");
while(stdin.hasNext()){
System.out.println("Please enter a name that you would like to search for: ");
String input = stdin.next();
for(int i = 0;i<length;i++){
if(input.equalsIgnoreCase(names[i])){
System.out.println("We found "+names[i]+" in our database!");
break;
}else{
continue;
}
}
}
}
}我只是没有得到我期待的输出,我不知道为什么。
发布于 2016-02-28 18:52:08
尝试一下,您应该trim()您的值,因为它们有额外的空间。
if(input.trim().equalsIgnoreCase(names[i].trim()))我已经运行了您的示例,它在使用trim()之后运行得很好,您错过了trim()
发布于 2016-02-28 18:49:20
创建一个独立的scanner类,通过line.You读取行,也可以使用BufferedReader。
final Scanner scanner = new Scanner(file);
while (scanner.hasNextLine()) {
final String str= scanner.nextLine();
if(str.contains(name)) {
// Found the input word
System.out.println("I found " +name+ " in file " +file.getName());
break;
}
}发布于 2016-02-28 18:57:25
如果您使用Java 8:
String[] names;
try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
names = stream.skip(1).toArray(size -> new String[size]);
} catch (IOException e) {
e.printStackTrace();
}https://stackoverflow.com/questions/35686687
复制相似问题