我试图使用 ID 从文本文件中搜索特定数据。 但我只能搜索并显示 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)
{
}
}
下面是我的文本文件:
T1001|维修|雷蒙德|李|3000.00|工作人员|abc123|
T1002|重绘|乔伊|谭|3000.00|工作人员|123456|
最佳答案
默认情况下,Scanner
类将第一行作为文件的输入。但是您必须读取所有行,因此最好使用 #nextLine
方法,然后使用 #split
方法从该行中提取各个值。请按照以下代码操作:
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)
{
}
}
}
关于java - 我试图使用 ID 从文本文件中搜索特定数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51909755/