java - 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|
解决方案
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)
{
}
}
}
推荐阅读
- spring-boot - 图像未保存在资源目录spring boot mvc应用程序下
- javascript - 试图将模拟数据传递给功能组件并遍历数组以在跨度中显示属性,出现类型错误无法访问模拟数据
- java - 从 Excel 为测验应用程序输入数据的更简单方法?
- php - 我需要将带有 mongodb 的 codeigniter 转换为 codeigniter 和 pdo 或 mysqli
- javascript - 使用 html 对话框中的输入字段中的值使用 Google Apps 脚本在 code.gs 中进行 var
- sql - SSMS:尝试查找连接服务器的 IP 地址
- python - 在 Python 中使用 Selenium 来单击带有 Java 的 HTML 标记不起作用
- c - 我正在尝试编写一个代码,该代码取每个值的总和,但同时也打印每个值
- javascript - 这个用于检查字符串是否为回文的 javascript 递归解决方案的大 O 是什么?
- c++ - 从向量 C++ 中擦除类元素