我正在尝试使用file writer向文本文件添加名称,并使用scanner类搜索名称。我的问题是,当我向文本文件中添加多个名称并搜索添加到文本文件中的名字时,显示的是第一个名称,但所有其他名称都不显示。这是密码
public class Test {
public static void main(String[] args) throws IOException {
menu();
}
public static void menu() throws IOException {
Scanner input = new Scanner(System.in);
System.out.println("1. Add name");
System.out.println("2. Done");
int choice = input.nextInt();
switch (choice) {
case 1: {
addName();
break;
}
case 2: {
verify();
break;
}
default: {
System.out.println("Invalid Selection");
break;
}
}
}
public static void addName() {
Scanner scan = new Scanner(System.in);
try {
FileWriter writer = new FileWriter("Names.txt", true);
writer.write("\r\n");
System.out.println("Enter Name: ");
writer.write(scan.nextLine());
writer.close();
System.out.println("name added to file");
menu();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void verify()
throws IOException {
Scanner textfile = new Scanner(new File("Names.txt"));
Scanner VerifyScnr = new Scanner(System.in);
System.out.print("Enter name: ");
String Name = VerifyScnr.next();
while (textfile.hasNext()) {
String search = textfile.next();
if (search.equalsIgnoreCase(Name)) {
System.out.println("This name is in the file");
menu();
} else {
System.out.println("This name is not in the file");
verify();
}
}
}
}
1条答案
按热度按时间eni9jsuy1#
试试这个