I'm trying to edit a player in my code and then update the values in my CSV file that I created but I am not sure about how to write the new values to the file itself. I know what I want to do but just not sure how about to do it. I am editing the amount paid and trying to update it in the file for the player.
Here are my classes:
Main class here
package squashapplication;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class SquashMain {
public static String MENU = "Options:\nA) Add player\nS) Show players\n G) Update Amount Paid\nX) Exit";
public static String FILE_NAME = "c:\\cis2232\\players.csv";
public static void main(String[] args) throws IOException {
Files.createDirectories(Paths.get("/cis2232"));
ArrayList<SquashPlayer> theList = new ArrayList();
loadPlayers(theList);
String choice = "";
do{
System.out.println(MENU);
choice = FileUtility.getInput().nextLine().toUpperCase();
switch(choice){
case "A":
SquashPlayer player = new SquashPlayer(true);
theList.add(player);
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILE_NAME, true);
bw = new BufferedWriter(fw);
bw.write(player.getCSV(true));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
break;
case "S":
System.out.println("Here are the players");
for (SquashPlayer SquashPlayer : theList) {
System.out.println(SquashPlayer);
}
break;
case "G":
System.out.println("Enter ID:");
int input = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
for(SquashPlayer id:theList){
if(id.getId() == input){
System.out.println("Enter in new amount paid:");
int newAmount = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
id.setAmountPaid(newAmount);
}
}
case "X":
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option");
break;
}
}while (!choice.equalsIgnoreCase("x"));
}
public static void loadPlayers(ArrayList squash){
System.out.println("Loading players from the list!");
int counter = 0;
try{
ArrayList<String> tester = (ArrayList<String>) Files.readAllLines(Paths.get(FILE_NAME));
for(String current:tester){
System.out.println("Loading: "+current);
SquashPlayer temp = new SquashPlayer(current);
squash.add(temp);
counter++;
}
}catch(IOException ex){
System.out.println("Error loading players from file.");
System.out.println(ex.getMessage());
}
System.out.println("Loaded players from file: "+ counter + " players");
}
}
SquashPlayer class here
package squashapplication;
import java.util.Scanner;
/**
*
*/
public class SquashPlayer {
private static int maxRegistrationId;
private int id;
private String name;
private String parentName;
private String phoneNumber;
private String email;
private int amountPaid;
public SquashPlayer() {
}
public SquashPlayer(boolean getFromUser){
System.out.println("Enter Full Name:");
this.name = FileUtility.getInput().nextLine();
System.out.println("Enter Parents name:");
this.parentName = FileUtility.getInput().nextLine();
System.out.println("Enter phone number:");
this.phoneNumber = FileUtility.getInput().nextLine();
System.out.println("Enter e-mail:");
this.email = FileUtility.getInput().nextLine();
System.out.println("Enter amount paid:");
this.amountPaid = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
this.id = ++ maxRegistrationId;
}
public SquashPlayer(int id, String name, int amountPaid , String phoneNumber, String parentName , String email ) {
this.id = id;
this.amountPaid = amountPaid;
this.name = name;
this.parentName = parentName;
this.email = email;
this.phoneNumber = phoneNumber;
}
public SquashPlayer(String[] parts) {
this(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2]), parts[3],parts[4], parts[5]);
if (Integer.parseInt(parts[0]) > maxRegistrationId) {
maxRegistrationId = Integer.parseInt(parts[0]);
}
}
public SquashPlayer(String csvValues) {
this(csvValues.split(","));
}
public String getCSV() {
return id + "," + name + "," + amountPaid + "," + phoneNumber + "," + email + "," + parentName;
}
public String getCSV(boolean withLineFeed){
if(withLineFeed){
return getCSV()+System.lineSeparator();
}else{
return getCSV();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "ID=" +id+ ", Name=" + name + ", email=" + email + ", Phone Number=" + phoneNumber + ", Amount Paid=" + amountPaid + ", Parent's Name: "+parentName;
}
}
This might help,
Instead of fw.write, which I believe that's what you use, use fw.append adding a new line character "\n" at the end.
Related
As you can see below I tried creating a switch case for choices
1. Name
2. Course then Name
3. Year Level then Name
4. Course then Year Level and the Name
5. Exit
I don't know how to use switch case so that I could sort everything according to the menu. I will be using comparable and I am only allowed to edit the method called compareTo. My mind is blank and I got no idea where to start.
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2
These are the inputs from text file
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Scanner;
import java.util.Vector;
public class Main {
/**
* #param args the command line arguments
*/
public static void main(String[] args) throws IOException {
try {
BufferedReader br = new BufferedReader(new FileReader("c://student.txt"));
char g;
int yl, I;
String ln, fn, id, cors, con;
Student v[] = new Student[4];
Scanner sc= new Scanner(System.in);
boolean en = true;
boolean ent = true;
for(i = 0; i < 4; i++){
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
v[i] = new Student(ln, fn, id, cors, g, yl);
}
while(en == true){
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("1. Name");
System.out.println("2. Course then Name");
System.out.println("3. Year Level then Name");
System.out.println("4. Course then Year Level and the Name");
System.out.println("5. Exit");
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("Choose Menu: ");
int choice = sc.nextInt();
switch(choice){
case 1 :
Arrays.sort(v);
display_array(v);
break;
case 2 :
Arrays.sort(v);
display_array(v);
break;
case 3 :
Arrays.sort(v);
display_array(v);
break;
case 4 :
Arrays.sort(v);
display_array(v);
break;
case 5 :
en = false;
System.out.println("\n\n \nTHANK YOU FOR USING THE PROGRAM!!");
break;
}
if(en != false){
System.out.println("Press [Enter key] to continue");
try{
System.in.read();
}catch(Exception e){
e.printStackTrace();
}
}
}
} catch (FileNotFoundException e) {
System.err.println("File not found");
} catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
public static void display_array(Student arr_v[]) throws IOException{
System.out.println("--------------------------------------");
for(int i = 0; i < arr_v.length; i++){
arr_v[i].display();
}
System.out.println("--------------------------------------");
}
}```
```
public class Student implements Comparable {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String ln, String fn, String id, String cors, char g, int yl) {
lastname = ln;
firstname = fn;
studentid = id;
course = cors;
gender = g;
yearlevel = yl;
}
public int compareTo(Object anotherObject) {
Student anotherStudent = (Student) anotherObject;
int compareResult =
this.course.compareTo(anotherStudent.lastname);
if(compare )
return 0;
}
public void display() {
System.out.printf("ID: %-8s Name: %-20s Sex: %c Course: %-8s Year: %d\n", studentid, (lastname + ", " + firstname), gender, course, yearlevel );
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
}```
public final class Student {
private final String id;
private final String firstName;
private final String lastName;
private final char gender;
private final String course;
private final int yearLevel;
public Student(String id, String firstName, String lastName, char gender, String course, int yearLevel) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.gender = Character.toUpperCase(gender);
this.course = course;
this.yearLevel = yearLevel;
}
public void display(PrintStream out) {
out.format("Name : %s, %s\n", lastName, firstName);
out.format("Student ID : %s\n", id);
out.format("Course : %s\n", course);
out.format("Gender : %s\n", gender);
out.format("Year Level : %d\n", yearLevel);
}
}
public static void main(String... args) throws FileNotFoundException {
File file = new File("c://student.txt");
List<Student> students = readStudents(file);
display(students);
}
private static List<Student> readStudents(File file) throws FileNotFoundException {
try (Scanner scan = new Scanner(file)) {
List<Student> students = new ArrayList<>();
while (scan.hasNext()) {
String id = scan.next();
String lastName = scan.next();
String firstName = scan.next();
char gender = scan.next().charAt(0);
String course = scan.next();
int yearLevel = scan.nextInt();
students.add(new Student(id, firstName, lastName, gender, course, yearLevel));
}
return students;
}
}
private static void display(List<Student> students) {
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
System.out.println("1. Name");
System.out.println("2. Course then Name");
System.out.println("3. Year Level then Name");
System.out.println("4. Course then Year Level and the Name");
System.out.println("5. Exit");
System.out.println("--------------------------------------");
System.out.println("--------------------------------------");
students.forEach(student -> {
student.display(System.out);
System.out.println();
});
}
All programmers need to learn how to debug their code. If you are using an IDE then I recommend that you learn how to use its debugger.
You have some calls to method readLine() that you do not need. In the below code, I have marked these lines as comments. I also incorporated the methods display_array() and main() into class Student just so everything would be in the one class, but you don't have to do that.
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
public class Student {
private String lastname, firstname, studentid, course;
private char gender;
private int yearlevel;
public Student(String id, String ln, String fn, char g, String cors, int yl) {
studentid = id;
lastname = ln;
firstname = fn;
gender = g;
course = cors;
yearlevel = yl;
}
private static void display_array(Student[] v) {
for (Student s : v) {
s.display();
}
}
public void display() {
System.out.println("Name : " + lastname + ", " + firstname);
System.out.println("Student ID: " + studentid);
System.out.println("Course : " + course);
System.out.println("Gender : " + gender);
System.out.println("Year Level: " + yearlevel);
}
public void setGender(char gender){
this.gender = gender;
}
public char getGender(){
return gender;
}
public void setLastname(String lastname){
this.lastname = lastname;
}
public String getLastname(){
return lastname;
}
public void setFirstname(String firstname){
this.firstname = firstname;
}
public String getFirstname() {
return firstname;
}
public void setStudentId(String studentid){
this.studentid = studentid;
}
public String getStudentId(){
return studentid;
}
public void setCourse(String course){
this.course = course;
}
public String getCourse(){
return course;
}
public void setYearLevel(int yearlevel){
this.yearlevel = yearlevel;
}
public int getYearLevel(){
return yearlevel;
}
public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("c:\\student.txt"));) {
char g;
int yl;
int i;
String ln;
String fn;
String id;
String cors;
Student v[] = new Student[Integer.parseInt(br.readLine())];
// br.readLine();
for (i = 0; i < v.length; i++) {
id = br.readLine();
ln = br.readLine();
fn = br.readLine();
// g = (char) br.read();
g = br.readLine().charAt(0);
cors = br.readLine();
yl = Integer.parseInt(br.readLine());
// if ((br.readLine()) != null)
// br.readLine();
v[i] = new Student(id, ln, fn, g, cors, yl);
}
display_array(v);
}
catch (FileNotFoundException e) {
System.err.println("File not found");
}
catch (IOException e) {
System.err.println("Unable to read the file.");
}
}
}
I also changed file student.txt. According to your code, the first line of the file needs to be the number of students in the file. In the sample file in your question, there are four students.
4
20192215
Ang
Bryan
m
BSCS
4
20192200
Santos
Charlie
m
BSIT
2
20192452
Chua
Leah
f
BSIS
4
20190012
Yee
John
m
BSCS
2
I have created class Patient (pojo), where I have declared variables.
I have added getter and setter methods, as well as a constructor:
public class Patient {
private String patientName;
private String phoneNumber;
private int age;
//generate getter and setter method
public String getPatientName() {
return patientName;
}
public void setPatientName(String patientName) {
this.patientName = patientName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
//generate constructor
public Patient(String patientName, String phoneNumber, int age) {
this.patientName = patientName;
this.phoneNumber = phoneNumber;
this.age = age;
}
}
I have created an interface PatientDetails and implemented the methods in the Hospital class.
public interface PatientDetails {
public void addpatient();
public void refreshPatient()throws IOException;
}
Here is how the methods are implemented:
public class Hospital implements PatientDetails {`
Scanner scan = new Scanner(System.in);
int token = 0;
String name, mobileNumber;
static HashMap<Integer, Patient> map = new HashMap<Integer, Patient>();
File file = new File("E:\\Patient\\pt.txt");
int age;
public void addpatient() {
BufferedWriter bufferedWriter = null;
FileWriter fileWriter = null;
try {
// true = append file
// write a data in a file
fileWriter = new FileWriter(file, true);
bufferedWriter = new BufferedWriter(fileWriter);
System.out.println("Enter the name");
scan.nextLine();
name = scan.nextLine();
System.out.println("Enter Mobile number must be 10 digit");
mobileNumber = scan.nextLine();
System.out.println("Enter the age");
age = scan.nextInt();
bufferedWriter.write("TokenNumber:" + token + "," + "PatientName:" + name + ",PhoneNumber:" + mobileNumber
+ ",Age :" + age + ";");
// for nextline
bufferedWriter.newLine();
// close file
bufferedWriter.close();
fileWriter.close();
System.out.println("yours Appoint cofirmed....\nPatient Name: " + name + "\nMobile number: " + mobileNumber
+ "\nToken number is: " + token + "\nAge is:" + age);
token++;
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Something went wrong");
e.printStackTrace();
}
}
#Override
public void refreshPatient() throws IOException {
Patient patient=new Patient(mobileNumber, mobileNumber, age);
String filePath = file.getPath();
System.out.println("refreshed successfully");
String line;
BufferedReader reader = new BufferedReader(new FileReader(filePath));
map=new HashMap<>();
while ((line = reader.readLine()) != null) {
String[] parts = line.split(":", 2);
if (parts.length >= 2) {
String key = parts[0];
String value = parts[1];
//map.put(Integer.parseInt(key), value);
} else {
System.out.println("ignoring line: " + line);
}
}
System.out.println(map);
reader.close();
}`)
I have added the patient name, age, and mobile number into the patient.txt file.
When I call the refresh method all the values should come to the map, but I am not getting the Patient class values into the map.
How to fix that?
you should split with , before :.
I've made an ArrayList of players that I want to search through to change the amount they have paid. I want to be able to enter in their ID, then be able to change their amount paid just for that player. I am also writing it to a CSV file but I am not sure how to update that file with the new value. I'm not sure about how to go about doing this.
What I want to do is just update a value in the ArrayList for a specific player based on player input on the registration ID, then I want to update that value in the file.
Here are my 3 classes that I have made: SquashPlayer
package squashapplication;
import java.util.Scanner;
/**
*
* #author Evan
*/
public class SquashPlayer {
private static int maxRegistrationId;
private int id;
private String name;
private String parentName;
private String phoneNumber;
private String email;
private int amountPaid;
public SquashPlayer() {
}
public SquashPlayer(boolean getFromUser){
System.out.println("Enter Full Name:");
this.name = FileUtility.getInput().nextLine();
System.out.println("Enter Parents name:");
this.parentName = FileUtility.getInput().nextLine();
System.out.println("Enter phone number:");
this.phoneNumber = FileUtility.getInput().nextLine();
System.out.println("Enter e-mail:");
this.email = FileUtility.getInput().nextLine();
System.out.println("Enter amount paid:");
this.amountPaid = FileUtility.getInput().nextInt();
FileUtility.getInput().nextLine();
this.id = ++ maxRegistrationId;
}
public SquashPlayer(int id, String name, int amountPaid , String phoneNumber, String parentName , String email ) {
this.id = id;
this.amountPaid = amountPaid;
this.name = name;
this.parentName = parentName;
this.email = email;
this.phoneNumber = phoneNumber;
}
public SquashPlayer(String[] parts) {
this(Integer.parseInt(parts[0]), parts[1], Integer.parseInt(parts[2]), parts[3],parts[4], parts[5]);
if (Integer.parseInt(parts[0]) > maxRegistrationId) {
maxRegistrationId = Integer.parseInt(parts[0]);
}
}
public SquashPlayer(String csvValues) {
this(csvValues.split(","));
}
public String getCSV() {
return id + "," + name + "," + amountPaid + "," + phoneNumber + "," + email + "," + parentName;
}
public String getCSV(boolean withLineFeed){
if(withLineFeed){
return getCSV()+System.lineSeparator();
}else{
return getCSV();
}
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAmountPaid() {
return amountPaid;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
return "ID=" +id+ ", Name=" + name + ", email=" + email + ", Phone Number=" + phoneNumber + ", Amount Paid=" + amountPaid + ", Parent's Name: "+parentName;
}
}
Here is my main class:
package squashapplication;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
public class SquashMain {
public static String MENU = "Options:\nA) Add player\nS) Show players\n G) Update Amount Paid\nX) Exit";
public static String FILE_NAME = "c:\\cis2232\\players.csv";
public static void main(String[] args) throws IOException {
Files.createDirectories(Paths.get("/cis2232"));
ArrayList<SquashPlayer> theList = new ArrayList();
loadPlayers(theList);
String choice = "";
do{
System.out.println(MENU);
choice = FileUtility.getInput().nextLine().toUpperCase();
switch(choice){
case "A":
SquashPlayer player = new SquashPlayer(true);
theList.add(player);
BufferedWriter bw = null;
FileWriter fw = null;
try {
fw = new FileWriter(FILE_NAME, true);
bw = new BufferedWriter(fw);
bw.write(player.getCSV(true));
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (bw != null) {
bw.close();
}
if (fw != null) {
fw.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
break;
case "S":
System.out.println("Here are the players");
for (SquashPlayer SquashPlayer : theList) {
System.out.println(SquashPlayer);
}
break;
case "G":
case "X":
System.out.println("Goodbye");
break;
default:
System.out.println("Invalid option");
break;
}
}while (!choice.equalsIgnoreCase("x"));
}
public static void loadPlayers(ArrayList squash){
System.out.println("Loading players from the list!");
int counter = 0;
try{
ArrayList<String> tester = (ArrayList<String>) Files.readAllLines(Paths.get(FILE_NAME));
for(String current:tester){
System.out.println("Loading: "+current);
SquashPlayer temp = new SquashPlayer(current);
squash.add(temp);
counter++;
}
}catch(IOException ex){
System.out.println("Error loading players from file.");
System.out.println(ex.getMessage());
}
System.out.println("Loaded players from file: "+ counter + " players");
}
}
And here is where I store my scanner in FileUtility:
package squashapplication;
import java.util.Scanner;
public class FileUtility {
private static Scanner input = new Scanner(System.in);
public static Scanner getInput() {
return input;
}
}
I wrote code and I can save same data in .csv file.
Now i want to read my data from csv file for example by UID.
I tried but can not get all my data by name.
Here is source
Pojo class code
public class Product {
private String UID;
private String name;
private String personalNumber;
#Override
public String toString() {
return "Product{" +
"UID='" + UID + '\'' +
", name='" + name + '\'' +
", personalNumber='" + personalNumber + '\'' +
", gender='" + gender + '\'' +
", issueState='" + issueState + '\'' +
", documentType='" + documentType + '\'' +
'}';
}
private String gender;
private String issueState;
private String documentType;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUID() {
return UID;
}
public void setUID(String UID) {
this.UID = UID;
}
public String getPersonalNumber() {
return personalNumber;
}
public void setPersonalNumber(String personalNumber) {
this.personalNumber = personalNumber;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getIssueState() {
return issueState;
}
public void setIssueState(String issueState) {
this.issueState = issueState;
}
public String getDocumentType() {
return documentType;
}
public void setDocumentType(String documentType) {
this.documentType = documentType;
}
}
And here is a main java class
public class ReadFromFile {
public static void main(String[] args) throws Exception {
File file = new File("C:\\\\cardReaderID\\2017-08-31.csv");
Scanner input = new Scanner(file);
Product[] products = new Product[0];
while(input.hasNext()) {
String UID = input.next();
String name = input.next();
String personalNumber = input.next();
Product newProduct = new Product();
newProduct.setUID(UID);
newProduct.setName(name);
newProduct.setPersonalNumber(personalNumber);
}
for (Product product : products) {
System.err.println(product);
}
}
How I can read all my data from csv file by name? I mean, UID,fullname and etc.
How i can solve my problem?
Thanks everyone
Here is a solution
public class CSVReader {
public static void main(String[] args) {
String csvFile= "C:\\\\cardReaderID\\2017-08-31.csv";
BufferedReader br = null;
String line = "";
String cvsSplitBy = ",";
try {
br = new BufferedReader(new FileReader(csvFile));
while ((line = br.readLine()) != null) {
// use comma as separator
String[] country = line.split(cvsSplitBy);
System.out.println("Country [code= " + country[4] + " , name=" + country[5] + "]");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I have to create an address book in java. I have gotten stuck in one area. When I add a second address it makes the first one null. I have areas commented out that I haven't gotten to yet so ignore those areas. I am at a loss why the first address turns to null.
import java.util.Scanner;
import java.io.IOException;
import java.io.File;
import java.io.FileWriter;
import java.io.FileNotFoundException;
class Program2 {
static Scanner s = new Scanner(System.in);
public static void main(String[] args) {
System.out.println("\nWelcome. Address book is loaded.");
loop: while(true) {
displayOptions();
int choice = s.nextInt();
switch(choice) {
case 1:
System.out.println("**Choice 1**");
AddressBook.display();
break;
case 2:
System.out.println("**Choice 2**");
System.out.print("First Name: ");
String firstName = s.next();
System.out.print("Last Name: ");
String lastName = s.next();
System.out.print("Phone Number: ");
String phone = s.next();
Contact test = new Contact(firstName, lastName, phone);
AddressBook.add(test);
break;
case 3:
System.out.println("**Choice 3**");
break;
case 4:
System.out.println("**Choice 4**");
break;
case 5:
break loop;
}
}
System.out.println("\nAddress book is saved to file.\n");
System.out.println("Good bye.\n");
System.exit(0);
}
private static void displayOptions() {
System.out.println("\nWhat would you like to do?");
System.out.println(" 1) Display all contacts\n" +
" 2) Add a contact\n" +
" 3) Remove a contact\n" +
" 4) Search a contact\n" +
" 5) Exit");
System.out.print("Your choice: ");
}
}
class Contact {
private String firstName;
private String lastName;
private String phone;
public Contact(String firstName, String lastName, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.phone = phone;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getPhone() {return phone;}
public void setFirstName(String firstName) {this.firstName = firstName;}
public void setLastName(String lastName) {this.lastName = lastName;}
public void setPhone(String phone) {this.phone = phone;}
/*public boolean equals(Object o) {
if (o instanceof Contact) {
Contact contacts = (Contact) o;
return (firstName.equals(contacts.getFirstName()) &&
lastName.equals(contacts.getLastName()));
}
return false;
}*/
public String toString() {
return firstName + " " + lastName + "\t\t" + phone;
}
}
class AddressBook {
public final static int CAPACITY = 100;
static private Contact[] contacts;
static private int count = 0;
static private String addressFile = "address.txt";
static File file = new File(addressFile);
public AddressBook(String addressFile) {
this.addressFile = addressFile;
}
public static boolean add(Contact c) {
contacts = new Contact[CAPACITY];
if (count < CAPACITY) {
contacts[count++] = c;
}
return false;
}
//public boolean remove(fullname) { }
//public Contact search(fullname) { }
public static void display() {
System.out.println("Name\t\t\tPhone Number");
System.out.println("-------------------------------------");
for (int i=0; i<count; i++) {
System.out.println(contacts[i]);
}
System.out.println("-------------------------------------");
}
/*public boolean load() {
try {
Scanner sF = new Scanner(file);
while (s.hasNext()) {
String line = s.nextLine();
System.out.println(line);
}
s.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
/*public boolean save() {
try {
FileWriter writer = new FileWriter(addressFile);
writer.write();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}*/
//public boolean contains(String firstName, String lastName) {
// return this.contacts.contains(firstName, lastName);
//}
}
Your add method overwrites the contacts array, so each time it is called, the references to the previous Contacts are lost :
public static boolean add(Contact c) {
contacts = new Contact[CAPACITY]; // remove this line
if (count < CAPACITY) {
contacts[count++] = c;
}
return false;
}
Instead of the removed line, initialize the contacts array only once :
static private Contact[] contacts = new Contact[CAPACITY];