首页 > 解决方案 > I was trying to search for the specific data from the text file by using the ID

问题描述

I was trying to search for the specific data from the text file by using the ID. But I was just able to search and display for the id T1001.

public static void main(String[] args){

    Scanner sc = new Scanner(System.in);
    String filepath = "Technician.txt";

    System.out.print("Enter ID : ");
    String searchTerm= sc.nextLine();



    readRecord(searchTerm,filepath);
}

public static void readRecord(String searchTerm,String filepath){

    boolean found = false;
    String techID="";
    String service="";
    String firstName="";
    String lastName="";
    String salary="";
    String position="";
    String password="";

    try
    {
    Scanner x = new Scanner(new File(filepath));
    x.useDelimiter("[\\|]");

    while(x.hasNext()&& !found)
    {
        techID = x.next();
        service=x.next();
        firstName=x.next();
        lastName=x.next();
        salary=x.next();
        position=x.next();
        password=x.next();


        if(techID.equals(searchTerm)){
            found = true;
        }

    }

    if(found)
    {
    System.out.print("ID: "+techID+"\n"+"Service : "+service+"\n"+"First Name: "+firstName+"\n"+"Last Name : "+lastName+"\n" + "Salary : "+salary
        +"\n" + "Position : "+position);
    }
    else
    {
        System.out.print("ID not found");
    }
    }
    catch(Exception e)
    {

    }


}

And below is my text file :

T1001|Repair|Raymond|Lee|3000.00|staff|abc123|

T1002|Repaint|Joey|Tan|3000.00|staff|123456|

标签: java

解决方案


By Default Scanner class takes the first line as input from your file. But you have to read all lines, so its better to use #nextLine method and then #split method to extract your individual values from the line. Follow the bellow code :

import java.util.Scanner;
import java.io.*;

public class example {
public static void main(String[] args){

Scanner sc = new Scanner(System.in);
String filepath = "Technician.txt";

System.out.print("Enter ID : ");
String searchTerm= sc.nextLine();



readRecord(searchTerm,filepath);
}

public static void readRecord(String searchTerm,String filepath){

try
{
Scanner x = new Scanner(new File(filepath));

while(x.hasNext())
{
  String values[] = x.nextLine().toString().split("\\|");


    if(values[0].equals(searchTerm)){
      System.out.print("ID: "+values[0]+"\n"+"Service : "+values[1]+"\n"+"First Name: "+values[2]+"\n"+"Last Name : "+values[3]+"\n" + "Salary : "+values[4]
          +"\n" + "Position : "+values[5] + "\n");
      return;
    }

}

System.out.print("ID not found");
}
catch(Exception e)
{

}

}
}

推荐阅读