How to display specific data from a file
- by user1067332
My program is supposed to ask the user for firstname, lastname, and phone number till the users stops. Then when to display it asks for the first name and does a search in the text file to find all info with the same first name and display lastname and phones of the matches.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class WritePhoneList
{
public static void main(String[] args)throws IOException
{
BufferedWriter output = new BufferedWriter(new FileWriter(new File(
"PhoneFile.txt"), true));
String name, lname, age;
int pos,choice;
try
{
do
{
Scanner input = new Scanner(System.in);
System.out.print("Enter First name, last name, and phone number ");
name = input.nextLine();
output.write(name);
output.newLine();
System.out.print("Would you like to add another? yes(1)/no(2)");
choice = input.nextInt();
}while(choice == 1);
output.close();
}
catch(Exception e)
{
System.out.println("Message: " + e);
}
}
}
Here is the display code, when i search for a name, it finds a match but displays the last name and phone number of the same name 3 times, I want it to display all of the possible matches with the first name.
import java.util.*;
import java.io.*;
import java.util.Scanner;
public class DisplaySelectedNumbers
{
public static void main(String[] args)throws IOException
{
String name;
String strLine;
try
{
FileInputStream fstream = new FileInputStream("PhoneFile.txt");
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
Scanner input = new Scanner(System.in);
System.out.print("Enter a first name");
name = input.nextLine();
strLine= br.readLine();
String[] line = strLine.split(" ");
String part1 = line[0];
String part2 = line[1];
String part3 = line[2];
//Read File Line By Line
while ((strLine= br.readLine()) != null)
{
if(name.equals(part1))
{
// Print the content on the console
System.out.print("\n" + part2 + " " + part3);
}
}
}catch (Exception e)
{//Catch exception if any
System.out.println("Error: " + e.getMessage());
}
}
}