帮助即时卡住..我们要制作两个程序,我们要求用户输入多少名员工,名字,姓氏,名称,然后将其存储到名为names.db的文件中。 ...我能够完成这个...我坚持第二个程序......假设这样做....通过要求用户输入员工名字来检索员工数据库,如果员工是发现然后打印该信息...如果没有,则打印未找到。
import java.util.Scanner;
import java.io.*;
public class RetrieveInfo
{
public static void main(String[] args) throws IOException
{
//create scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
//open file
File file = new File("Employee.db");
Scanner inputFile = new Scanner(file);
//ask for employee name
System.out.print("enter the name of the employee. ");
String firstName =keyboard.nextLine();
//here is where im stuck...read the file and check of the empoyee is
here. We are learning about loops some im pretty sure its going to be a loop
}
}
答案 0 :(得分:0)
你应该通过你的线,如果数据在当前行,然后打印它。阅读完文件后:
String expectedemployee = null
for(String line : Files.readAllLines(Paths.get("/path/to/file.txt")) {
if(line.contains(firstName) {
expectedemployee = line;
break;
}
}
if(expectedemployee != null) {
// print
} else {
// you don't have any employee corresponding
}
或者您可以使用BufferedReader。
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
String line;
while ((line = br.readLine()) != null || expectedemployee != null) {
if(line.contains(firstName) {
expectedemployee = line;
break;
}
}
}
答案 1 :(得分:0)
使用数据库而不是文件对于这种类型会更好。如果你想要文件,那么你应该尝试使用对象输入/输出流。