2016-03-20 68 views
0

我相信你可以告訴,但我是新來的java。 反正我試圖從一個人鍵入一個名稱後從txt文件中搜索時讀取下面的3行,當文件中有其他名稱和信息時。信息從另一個程序放到txt文件中,該程序詢問了名字,姓氏,身份證號碼和多年的經驗,並將其打印在單獨的行中。這是我迄今爲止所擁有的。從.txt文件讀取名稱後,如何打印下3行?

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); 
    } 
+0

你也可以使用循環,比如'for'。 – Akbari

+1

你似乎已經從閱讀'keyboard'切換到閱讀'inputFile'。 –

+0

我想着如何使用for循環,但想不到如何。 – Ryfool

回答

0

可以使用.hasNext方法在文件

這裏閱讀線是我的僞代碼:

else 
{ 

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

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

      } 

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

公共類阿貝貝{ 公共靜態無效的主要( 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); 
     } 
}}