繁体   English   中英

从.txt文件中读取名称后,如何打印下3行?

[英]How can I print the next 3 lines after reading a name from a .txt file?

我敢肯定你会说出来的,但是我是java的新手。 无论如何,当文件中存在其他名称和信息时,我尝试从一个人键入名称以从txt文件中搜索后读取接下来的3行。 该信息从另一个程序输入txt文件,该程序询问名字,姓氏,身份证号和工作年限,并将它们打印在单独的行上。 到目前为止,这就是我所拥有的。

System.out.println("Please enter first name of employee.");
  String employeeName = keyboard.nextLine();    

  // Check to see if the name is in the file
  // And for some reason if the name is in it, it says that it's not
  if(fileName.contains(employeeName))
  {
     System.out.println("Sorry, that employee is not in the file.");
  }
  else
  {                
     // Read the last name.
     String lastName = inputFile.nextLine();
     System.out.println(lastName);

     // Read the employee number
     String employeeID = inputFile.nextLine();
     System.out.println(employeeID);

     // Read the years of experience
     String years = inputFile.nextLine();
     System.out.println(years);
  }

您可以使用.hasNext方法读取文件中的行

这是我的伪代码:

else
{

String[] name;
int[] id;
int[] yearsofexp;

while (filename.hasNext()) 
            {
                name = filename.nextLine(); 
                id = filename.nextInt;
                yearsofexp = filename.nextInt();

            }

}
    create a file "myFile.txt" and save it in the same folder with your code.

公共类Abebe {公共静态void main(String [] args)抛出FileNotFoundException {

        Scanner keyboard= new Scanner(System.in);

        System.out.println("Please enter first name of employee.");


        String employeeName = keyboard.nextLine();

      File fileName= new File("myFile.txt");  // open the file

        Scanner inputFile= new Scanner(fileName); // read in the file

        if(!inputFile.hasNext(employeeName))  // here you are checking if the name you entered is available in your file
        {
            System.out.println("Sorry, that employee is not in the file.");
        }
        else
        {
            // Read the last name.
            String lastName = inputFile.nextLine();
            System.out.println(lastName);

            // Read the employee number
            String employeeID = inputFile.nextLine();
            System.out.println(employeeID);

            // Read the years of experience
            String years = inputFile.nextLine();
            System.out.println(years);
        }
}}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM