how should i retrive file of text1 to be used as a login information..
as i already enter the details in the registration part.. i would like to use the first name and staff id as a username and password for login part..
p/s: im so weak at coding..so please forgive my messy coding :)
here is my code.
import java.util.Scanner;
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.FileReader;
public class TestMyException12 {
static void clear() {
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter your last name:\n");
Scanner scan1 = new Scanner(System.in);
String text1 = scan.nextLine();
System.out.println("Enter your NRIC:\n");
Scanner scan2 = new Scanner(System.in);
String text2 = scan.nextLine();
System.out.println("Enter your Staff ID:\n");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
System.out.println("Enter your position:\n");
Scanner scan4 = new Scanner(System.in);
String text4 = scan.nextLine();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.write(text1);
writer.write(text2);
writer.write(text3);
writer.write(text4);
writer.newLine();
writer.close();
System.err.println("Your input data " + text.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else {
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter Password : ");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
if (scan.equals(text) && scan.equals(text3)) {
clear();
System.out.println("Access Granted! Welcome!");
} else if (scan.equals(text)) {
System.out.println("Invalid Password!");
} else if (scan.equals(text3)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Please register first!\n");
}
}
}
}
It's easy, make it like this :
package com.coder.singleton;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class TestMyException12 {
static void clear() {
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {
}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
StringBuilder sb = new StringBuilder();
String text = "";
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
text = input1.next();
sb.append(text + " ");
System.out.println("Enter your last name:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your NRIC:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your Staff ID:\n");
text = input1.next();
sb.append(text+ " ");
System.out.println("Enter your position:\n");
text = input1.next();
sb.append(text+ " ");
input1.close();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(sb.toString());
writer.newLine();
writer.close();
System.err.println("Your input data " + sb.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else {
String savedName = "";
String savedPassword = "";
try {
FileInputStream fis = new FileInputStream(new File("text1.txt"));
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis, "UTF-8"));
String word = "";
String [] arr = null;
while ((word = bufferedReader.readLine())!= null) {
arr = word.split("\\s+");
}
savedName = arr[0];
savedPassword = arr[2];
bufferedReader.close();
} catch (Exception e) {
// TODO: handle exception
}
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
String userName = input1.next();
System.out.println("Enter Password : ");
String password = input1.next();
if (userName.equals(savedName) && password.equals(savedPassword)) {
clear();
System.out.println("Access Granted! Welcome!");
}else if (userName.equals(savedName) && !password.equals(savedPassword)) {
System.out.println("Invalid Password!");
} else if (!userName.equals(savedName) && password.equals(savedPassword)) {
System.out.println("Invalid Username!");
} else {
System.out.println("Please register first!\n");
}
}
}
}
the first,you should insert separator(like newLine) when save the register information to file text1,if not ,you can't distinguish information fields.for example:
fWriter = new FileWriter("d:\\tmp\\pass.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.newLine(); //separator string
writer.write(text1);
writer.newLine();
writer.write(text2);
writer.newLine();
writer.write(text3);
writer.newLine();
writer.write(text4);
writer.newLine();
writer.close();
and then,you should retrieve the register information(just first name and staff) form file text1.txt
BufferedReader reader=new BufferedReader(new FileReader("text1.txt"));
String firstName = reader.readLine();
reader.readLine();
reader.readLine();
String passWord=reader.readLine();
final,compare input information with read information.
if (firstName.equals(text) && passWord.equals(text3)) {
System.out.println("Access Granted! Welcome!");
}
At Registration
You have to insert some delimiter (‘,’, ‘.’, ‘:’, ‘_’, ‘- ‘etc.…) at registration time.
Now Hear I am using “#” delimiter.
After insert that data and Delimiter.
Now At read time You have to split with That Delimiter you can access that data. in array
See Bellow code…
import java.util.Scanner;
import java.io.*;
import java.io.BufferedWriter;
import java.io.FileWriter;
public class TestMyException12
{
static void clear(){
try {
if (System.getProperty("os.name").contains("Windows"))
new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
else
Runtime.getRuntime().exec("clear");
} catch (IOException | InterruptedException ex) {}
}
public static void main(String[] args) {
System.out.println("1.Please register for new staff\n2.Staff login\n");
Scanner input1 = new Scanner(System.in);
FileWriter fWriter = null;
BufferedWriter writer = null;
int choice = input1.nextInt();
if (choice == 1) {
System.out.println("======================Staff Registration==================\n");
System.out.println("Please enter your personal details below:\n");
System.out.println("Enter your first name:\n");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter your last name:\n");
Scanner scan1 = new Scanner(System.in);
String text1 = scan.nextLine();
System.out.println("Enter your NRIC:\n");
Scanner scan2 = new Scanner(System.in);
String text2 = scan.nextLine();
System.out.println("Enter your Staff ID:\n");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
System.out.println("Enter your position:\n");
Scanner scan4 = new Scanner(System.in);
String text4 = scan.nextLine();
try {
fWriter = new FileWriter("text1.txt");
writer = new BufferedWriter(fWriter);
writer.write(text);
writer.write("#");
writer.write(text1);
writer.write("#");
writer.write(text2);
writer.write("#");
writer.write(text3);
writer.write("#");
writer.write(text4);
writer.close();
System.err.println("Your input data " + text.length() + " was saved.");
} catch (Exception e) {
System.out.println("Error!");
}
}
else
{
System.out.println("======================Staff Login===========================");
System.out.println("\nLogin(Use your first name as username and id as password)");
System.out.println("Enter Username : ");
Scanner scan = new Scanner(System.in);
String text = scan.nextLine();
System.out.println("Enter Password : ");
Scanner scan3 = new Scanner(System.in);
String text3 = scan.nextLine();
String datafile = "";
try
{
FileReader fr = new FileReader("text1.txt");
int i;
while((i = fr.read()) != -1)
{
datafile = datafile+(char)i; // store all data into String obj from File
}
}
catch(Exception e)
{
System.out.println("Error In Login : "+e);
}
String[] userval = datafile.split("#"); // split that data and create part of that data
for(int i = 0 ; i < userval.length ; i++)
{
System.out.println(i+">>>>>"+userval[i]);
}
// userval[] is array that is store all data from that file into part
// after you can put any condition
//System.out.println(text+">>>>>"+userval[0]);
//System.out.println(text3+">>>>>"+userval[3]);
if(text.equals(userval[0]) && text3.equals(userval[3]))
{
clear();
System.out.println("Access Granted! Welcome!");
}
else
{
System.out.println("Please register first!\n");
}
}
}
}
Related
I am creating a hospital management system in which I have 2 classes namely AddDoctor and AddPatient which takes the input from user about their details and stores them into their respective files. I now want to create an Appointment class in which I can assign a patient with a certain ID to a doctor with a certain ID which are read from the files. This would be very easy if Java supported multiple inheritance, but since it doesn't, I'm stuck on how I could do this task.
Following is my AddDoctor class
class AddDoctor{
int did;
int dage;
long dphno;
String dname;
String dgender;
String dqualification;
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
void input() throws IOException{
System.out.print("Enter Doctor's Name:");
dname = br.readLine();
Random rand = new Random();
did = rand.nextInt((9999 - 100) + 1) + 10;
System.out.print("Enter Doctor's Phone Number:");
dphno = Long.parseLong(br.readLine());
System.out.print("Enter Doctor's Age:");
dage = Integer.parseInt(br.readLine());
System.out.print("Enter Doctor's Gender:");
dgender = br.readLine();
System.out.print("Enter Doctor's Qualification:");
dqualification = br.readLine();
}
void delete() throws FileNotFoundException, IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("DoctorDetails.txt");
File tempFile = new File("myTemp.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the ID of the Doctor you wish to delete: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
void search() throws IOException{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID of the Doctor To Search:");
String did=scan.next();
String line="";
try{
FileInputStream fin = new FileInputStream("DoctorDetails.txt");
Scanner sc = new Scanner(fin);
while(sc.hasNextLine()){
line=sc.nextLine();
if(line.startsWith(did))
System.out.println(line+" ");
}
sc.close();
}
catch(IOException e){
e.printStackTrace();
}
}
void display(){
try{
BufferedReader br=new BufferedReader(new FileReader("DoctorDetails.txt"));
String s="";
while((s=br.readLine())!=null){
String data[]=new String[6];
data=s.split(" ");
for(int i=0;i<6;i++){
System.out.print(data[i]+"\t");
}
System.out.println();
}
br.close();
}
catch(Exception e){
}
}
};
//Class WriteD to Write Doctor Details in a text file where the details are fetched from the Class AddDoctor
class WriteD extends AddDoctor {
void write() {
try(FileWriter fw = new FileWriter("DoctorDetails.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(did + " " + dname + " " + dphno + " " + dage + " " + dgender + " " + dqualification);
}catch(IOException e){
e.printStackTrace();
}
}
};
Following is my AddPatient Class
class AddPatient extends People{
String pillness;
String pregisterdate;
InputStreamReader in = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(in);
void input() throws IOException{
System.out.print("Enter Patient's Name:");
name = br.readLine();
Random rand1 = new Random();
id = rand1.nextInt((9999 - 100) + 1) + 10;
System.out.print("Enter Patient's Phone Number:");
phno = Long.parseLong(br.readLine());
System.out.print("Enter Patient's Age:");
age = Integer.parseInt(br.readLine());
System.out.print("Enter Patient's Gender:");
gender = br.readLine();
System.out.print("Enter Patient's Illness:");
pillness = br.readLine();
System.out.print("Enter Patient's Registration Date:");
pregisterdate = br.readLine();
}
void delete() throws FileNotFoundException, IOException{
Scanner in = new Scanner(System.in);
File inputFile = new File("PatientDetails.txt");
File tempFile = new File("myTemp2.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String currentLine;
String lineToRemove;
System.out.println("Enter the ID of the Patient you wish to delete: ");
lineToRemove = in.next();
while((currentLine = reader.readLine()) != null) {
String trimmedLine = currentLine.trim();
if(trimmedLine.startsWith(lineToRemove)) continue;
writer.write((currentLine) + System.getProperty("line.separator"));
}
writer.close();
reader.close();
Files.move(tempFile.toPath(), inputFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
void search() throws IOException{
Scanner scan=new Scanner(System.in);
System.out.println("Enter the ID of the Patient To Search:");
String did=scan.next();
String line="";
try{
FileInputStream fin = new FileInputStream("PatientDetails.txt");
Scanner sc = new Scanner(fin);
while(sc.hasNextLine()){
line=sc.nextLine();
if(line.startsWith(did))
System.out.println(line);
}
sc.close();
}
catch(IOException e){
e.printStackTrace();
}
}
void display(){
try{
BufferedReader br=new BufferedReader(new FileReader("PatientDetails.txt"));
String s="";
while((s=br.readLine())!=null){
String data[]=new String[7];
data=s.split(" ");
for(int i=0;i<7;i++){
System.out.print(data[i]+"\t");
}
System.out.println();
}
br.close();
}
catch(Exception e){
}
}
};
class WriteP extends AddPatient {
void write() {
try(FileWriter fw = new FileWriter("PatientDetails.txt",true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter out = new PrintWriter(bw))
{
out.println(String.format("%-1s %-1s %-1s %-1s %-1s %-1s %-1s",id,name,phno,age,gender,pillness,pregisterdate));
}catch(IOException e){
e.printStackTrace();
}
}
};
Simple solution is using composition create object of doc and patient in appointment class and get doc and patient id from user or create one using objects and write it in third file.
In case of Id you need to search info from file.
In case of new information, as you will be creating object of doctor and patient. first right them in their files and then store data in third file as you want.
If it answer your question let me know.
Create an appointment class and use a search method that accepts the ids to look for (which would look similar to the search methods you already have) then utilize code similar to your write to write to the new file.
I am working on a MabLibs project that is supposed to iterate through a file, prompt you with anything contained in a <> block and allow you to write over to a new file.
I cannot figure out how to use a Scanner to read a file and turn that into a string so I can use the .length() method to iterate a for loop through the file to find these <> blocks.
I can only use Scanner and can't use array lists, so unfortunately the for loop is the only way I can do this.
Here's the code:
import java.io.*;
import java.util.*;
public class MadLibs {
public static void main(String[] args)
throws FileNotFoundException {
intro();
madLib();
}
public static void intro() {
System.out.println("Welcome to the game of Mad Libs.");
System.out.println("I will ask you to provide various words");
System.out.println("and phrases to fill in a story.");
System.out.println("The result will be written to an output file.");
System.out.println();
}
public static void madLib() throws FileNotFoundException {
Scanner input = new Scanner(System.in);
System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
String r = input.next();
while (!(r.equalsIgnoreCase("c") || r.equalsIgnoreCase("v")
|| r.equalsIgnoreCase("q"))) {
System.out.println("(C)reate mad-lib, (V)iew mad-lib, (Q)uit? ");
}
if (r.equalsIgnoreCase("v")) {
viewFile();
}
else if (r.equalsIgnoreCase("c")) {
createWord();
}
}
public static void createWord() throws FileNotFoundException {
System.out.println("Input file name: ");
Scanner viewFile = new Scanner(System.in);
String toRead = viewFile.nextLine();
File f = new File(toRead);
while (!f.exists()) {
System.out.println("File Not Found. Try again: ");
toRead = viewFile.nextLine();
f = new File(toRead);
}
Scanner input1 = new Scanner(new File(toRead));
String input2 = input1;
PrintStream output = new PrintStream(new File(toRead));
while (input1.hasNext()) {
String input = input1.next();
for (int i = 0; i < input2.length(); i++) {
if (input.startsWith("<") && input.endsWith(">")) {
String token = input.substring(1, input.length() - 1);
System.out.println("Please input a: " + token);
Scanner scan = new Scanner(System.in);
String replacement = scan.nextLine();
token = token.replace(token, replacement);
output.print(token);
}
}
}
}
public static void viewFile() throws FileNotFoundException {
System.out.println("Input file name: ");
Scanner viewFile = new Scanner(System.in);
String toRead = viewFile.nextLine();
File f = new File(toRead);
while (!f.exists()) {
System.out.println("File Not Found. Try again: ");
toRead = viewFile.nextLine();
f = new File(toRead);
}
Scanner input1 = new Scanner(new File(toRead));
System.out.println();
while (input1.hasNextLine()) {
System.out.println(input1.nextLine());
}
}
}
Any help is greatly appreciated.
I'm trying to write a program which will take user input from a list of options then either:
write to a file
alter an existing file or
delete a file.
At the moment I'm stuck on just writing to the file from the user input. I have to use regex notation for each of the users input as seen in the snippet. Any help or guidance on what i could do will be highly appreciated, and yes there are a lot of errors right now. Thanks!
import java.io.*;
import java.util.Scanner;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
private UserInput[] list;
class Input {
public static void main(String[] args) {
Scanner in = (System.in);
string Exit ="False";
System.out.println("person details");
System.out.println("");
System.out.println("Menu Options:");
System.out.println("1. Add new person");
System.out.println("2. Load person details ");
System.out.println("3. Delete person Entry");
System.out.print("Please select an option from 1-5\r\n");
int choice = in.nextLine();
if (choice == 1)
system.out.println("you want to add a new person deails.");
AddStudnet();
else if (choice == 2){
system.println("would you like to: ");
system.println("1. Load a specific entry");
system.println("2. Load ");
}
//Error checking the options
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
int input = Integer.parseInt(br.readLine());
if(input < 0 || input > 5) {
System.out.println("You have entered an invalid selection, please try again\r\n");
} else if(input == 5) {
System.out.println("You have quit the program\r\n");
System.exit(1);
} else {
System.out.println("You have entered " + input + "\r\n");
}
} catch (IOException ioe) {
System.out.println("IO error trying to read your input!\r\n");
System.exit(1);
}
}
}
//Scanner reader = new Scanner(System.in);{ // Reading from System.in
//System.out.println("Please enter your name: ");
//String n = reader.nextLine();
//}
// File file = new File("someFile.txt", True);
// FileWriter writer = new FileWriter(file);
// writer.write(reader);
// writer.close();
public static void addPerson(String args[]) throws IOException{
class input Per{
scanner in = new scanner (system.in);
system.out.print("Please enter you Name: ");
String name = in.nextLine()
final Pattern pattern = Pattern.compile("/^[a-z ,.'-]+$/i");
if (!pattern.matcher(name).matches()) {
throw new IllegalArgumentException("Invalid String");
//String Name = regex ("Name")
//regex below for formatting
system.out.println("Please enter your Job title:");
//String CourseNum = regex ("JobTitle");
system.out.println("Please enter your Town:");
//String Town = regex("Town");
system.out.println("Please enter your postcocde:");
//String postcocde = regex("postcocde");
system.out.println("Please enter your street:");
//String Street = regex ("Street");
system.out.println("Please enter your House Number:");
//String HouseNum = regex ("HouseNum");
}
}
//public static void
Is not clear that you look for " i'm stuck on just writing to the file"
here exemple on how to create/write to a file
String export="/home/tata/test.txt";
if (!Files.exists(Paths.get(export)))
Files.createDirectory(Paths.get(export));
List<String> toWrite = new ArrayList();
toWrite.add("tata");
Files.write(Paths.get(export),toWrite);
look at java tm
https://docs.oracle.com/javase/tutorial/essential/io/file.html
lio
We have managed to get the code to display the first employee's details, however, the other 2 employee details have it been displayed. I am not sure how to append them. I am not sure if the printWriter is the right thing to out put the code and of not then, what would be best?
The code is below :)
public static void main(String[] args) throws IOException{
Scanner scan = new Scanner(System.in);
File employeeDetails = new File("Employees.txt");
PrintWriter pw = new PrintWriter(new FileWriter(employeeDetails, true));
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);
try{
boolean repeat = false;
System.out.println("Enter name: ");
String name = scan.next();
pw.println("name: " + name);
System.out.println("Enter job title: ");
String jobTitle = scan.next();
pw.println("Job title: " + jobTitle);
do{
try{
System.out.println("Enter age: ");
int age = scan.nextInt();
pw.println("Age: " + age);
repeat = true;
}
catch(InputMismatchException ex){
System.err.println("Invalid age please enter a whole number.");
scan.next();
continue;
}
}while(repeat==false);
do{
try{
System.out.println("Enter salary per year: ");
double salary = scan.nextDouble();
pw.println("Salary: " + salary);
repeat = false;
}
catch(InputMismatchException ex){
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
catch(MissingFormatArgumentException ex){
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
}while(repeat);
}finally{
pw.close();
fw.close();
}
}
scan.close();
}
}
So you problem is that each time in for loop you create a new file(deleting the other)
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);
put it outside
You don't need fw:
for(int i=0; i<3; i++){
FileWriter fw = new FileWriter("Employees.txt", true);// remove this line
...
and also remove this line:
fw.close();
otherwise you'll get NullPointerException
Your problem is that you keep closing pw. Move the close of pw after the for loop. I have modified your code and the following works:
public static void main(String[] args) throws IOException {
Scanner scan = new Scanner(System.in);
File employeeDetails = new File("Employees.txt");
PrintWriter pw = new PrintWriter(new FileWriter(employeeDetails, true));
for (int i = 0; i < 3; i++) {
//FileWriter fw = new FileWriter("Employees.txt", true);
try {
boolean repeat = false;
System.out.println("Enter name: ");
String name = scan.next();
pw.println("name: " + name);
System.out.println("Enter job title: ");
String jobTitle = scan.next();
pw.println("Job title: " + jobTitle);
do {
try {
System.out.println("Enter age: ");
int age = scan.nextInt();
pw.println("Age: " + age);
repeat = true;
} catch (InputMismatchException ex) {
System.err.println("Invalid age please enter a whole number.");
scan.next();
continue;
}
} while (repeat == false);
do {
try {
System.out.println("Enter salary per year: ");
double salary = scan.nextDouble();
pw.println("Salary: " + salary);
repeat = false;
} catch (InputMismatchException ex) {
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
} catch (MissingFormatArgumentException ex) {
System.err.println("Invalid salary please enter a decimal.");
scan.next();
continue;
}
} while (repeat);
} finally {
//pw.close();
//fw.close();
}
}
pw.close();
scan.close();
}
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());
}
}
}
you need to split your line and set your parts inside the while loop:
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);
}
}