我的程序应该询问用户姓名,姓氏和电话号码,直到用户停止。然后何时显示它要求输入名字并在文本文件中搜索以查找具有相同名字的所有信息并显示匹配的姓氏和电话。
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);
}
}
}
这是显示代码,当我搜索名称时,它找到一个匹配但显示相同名称的姓氏和电话号码3次,我希望它显示所有可能的匹配名字。
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());
}
}
}
答案 0 :(得分:0)
你需要分割你的线并在while循环中设置你的部分:
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();
String[] line;
String part1, part2, part3;
//Read File Line By Line
while ((strLine= br.readLine()) != null)
{
line = strLine.split(" ");
part1 = line[0];
part2 = line[1];
part3 = line[2];
if(name.equals(part1))
{
System.out.print("\n" + part2 + " " + part3);
}
}