输入字符串未等同于文件中的字符串



我是一个新手,这个程序是关于从文本文件中读取名称的,但我无法通过它。

Scanner scan = new Scanner(System.in);
System.out.println("enter file to read");
String file = scan.nextLine();
try (Scanner scanner = new Scanner(Paths.get(file))) {
System.out.println("Enter name to validate, no entry will close");
while (scanner.hasNextLine()) {
String name = scan.nextLine();
String row = scanner.nextLine();
if (name.equals(row)) {
System.out.println("Entry Permitted");
} else if (name.isEmpty()) {
break;
} else {
System.out.println("Entry Denied");
}
}
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
}

以下是文件中的字符串:

Taylor Swift        
Kylie Jenner        
Kanye West      
Lionel Messi        
Ed Sheeran      
Cristiano Ronaldo   
Neymar
The Eagles      
Phil McGraw     
Saul "Canelo" Alvarez

虽然前面的答案有效。。。我们可以";流";为解决方案添加现代Java功能。

public static void main(String[] args) {
try (Scanner scanner = new Scanner(System.in)) {
System.out.println("Enter file of names to read ...r");
Set<String> names = Files.readAllLines(Paths.get(scanner.nextLine()))
.stream()
.map(String::trim)
.collect(Collectors.toSet());
System.out.println("Enter a name to validate, or a blank entry to exit ...r");
String name;
while (scanner.hasNextLine()) {
name = scanner.nextLine().trim();
if (name.isEmpty()) {
System.out.println("auf Wiedersehen");
break;
}
System.out.println(String.format("Entry %s", names.contains(name) ? "Permitted" : "Denied"));
}
} catch (Exception e) {
e.printStackTrace();
}
}

相关内容

  • 没有找到相关文章

最新更新