Arraylist read from file outputs twice - java

I have an ArrayList of items - name, account number and balance read from a .txt file. Why is the output twice? (I've only 4 lines in my file each containing- name; account number; balance)
I want things above blue line only. Why is it displaying twice?
This is my class to retrieve from file and print
class BankAccount{ //core banking facilities
PrintStream pw=System.out;
protected String name;
protected long accountNumber;
protected float balance=0;
public String choiceList="\n1.AddAccount\n2.Withdraw\n3.Deposit\n4.MyAccount";
public BankAccount(String name,long accountNumber,float balance){
this.accountNumber=accountNumber;
this.name=name;
this.balance = balance;
}
public String getName(){
return this.name;
}
public long get_Account_no(){
return this.accountNumber;
}
public float get_Balance(){
return this.balance;
}
public BankAccount(){//loads from file to arraylist
BufferedReader in = null;
ArrayList <BankAccount> customer_list=new ArrayList<BankAccount>();
try {
in = new BufferedReader(new FileReader("bankfile.txt"));
String str;
while ((str = in.readLine()) != null) {
String[] temp_list=str.split(";");
accountNumber=Long.parseLong(temp_list[1]);
balance=Float.parseFloat(temp_list[2]);
BankAccount customer = new BankAccount(temp_list[0],accountNumber,balance);
customer_list.add(customer);
}
}catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} finally {
if (in != null) {
try{ in.close();
} catch(Exception e){e.printStackTrace();}
}
}
for(BankAccount c: customer_list) pw.println(c.getName()+" "+c.get_Balance()+"\n");
}
}
and my main is-
class banker {
public static void main(String args[]){
additional_functionality af=new additional_functionality();
BankAccount ba=new BankAccount();
ba.pw.println("This is.. \n \t\tTHE BANK\nplease wait...");
String ch=JOptionPane.showInputDialog(ba.choiceList);
Integer choice=Integer.parseInt(ch);
switch(choice){
case 1: af.addAcount();
break;
case 4: //af.findAccount();
break;
default: JOptionPane.showMessageDialog(null,"Wrong Choice!","ERR",JOptionPane.ERROR_MESSAGE);
}System.exit(0);
}
my text file is-
bankfile.txt

Sorry, i'm not getting error. Hope this will helps you. I think that problem is that you twice run this constructor. Also, I run your code. And it's works.
My Main.java
public class Main {
public static void main(String[] args) {
// write your code
new BankAccount();
}
}
My file bankfile.txt
lala;0;0
coca;0;1
bola;1;1
My BankAccount.java
import java.io.*;
import java.util.ArrayList;
public class BankAccount {
private String name;
private long accountNumber;
private float balance;
public BankAccount(){//loads from file to arraylist
BufferedReader in = null;
ArrayList<BankAccount> customer_list=new ArrayList<BankAccount>();
try {
in = new BufferedReader(new FileReader("bankfile.txt"));
String str;
while ((str = in.readLine()) != null) {
String[] temp_list=str.split(";");
accountNumber=Long.parseLong(temp_list[1]);
balance=Float.parseFloat(temp_list[2]);
BankAccount customer = new BankAccount(temp_list[0],accountNumber,balance);
customer_list.add(customer);
}
for(BankAccount c: customer_list) System.out.println(c.getName()+" "+c.get_Balance());
}catch (FileNotFoundException e) {e.printStackTrace();
} catch (IOException e) { e.printStackTrace();
} finally {
if (in != null) {
try{ in.close();
} catch(Exception e){e.printStackTrace();}
}
}
}
public BankAccount(String name, Long accountNumber, float balance){
this.name = name;
this.balance = balance;
this.accountNumber = accountNumber;
}
public String getName() {
return name;
}
public long getAccountNumber() {
return accountNumber;
}
public float get_Balance() {
return balance;
}
}

Related

I'm doing a student management project in Java and get Serializable Exception errors

I am doing a basic student management app which runs in console with just 2 functions: Add student and show student list. But I get errors in Serializable Exception though I implements Serialization. My classes as below.
Class Student
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private int id;
private int gender;
private float gpa;
private static final long serialVersionUID = 1L;
public Student() {}
public Student(String name, int id, int gender, float gpa) {
super();
this.name = name;
this.id = id;
this.gender = gender;
this.gpa = gpa;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int isGender() {
return gender;
}
public void setGender(int gender) {
this.gender = gender;
}
public float getGpa() {
return gpa;
}
public void setGpa(float gpa) {
this.gpa = gpa;
}
}
StudenDAO class
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.SerializablePermission;
import java.util.ArrayList;
import java.util.List;
import javax.sql.rowset.serial.SerialException;
public class StudentDAO {
private static final String STUDENT_FILE_NAME = "studentRecord.txt";
/**
* save list student to file
* #param studentList: list student to save
*/
public void write(List<Student> studentList) {
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(new File(STUDENT_FILE_NAME));
oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
closeStream(fos);
closeStream(oos);
}
}
/**
* read list student from file
* #return list student
*/
public List<Student> read() throws SerialException {
List<Student> studentList = new ArrayList<>();
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(new File(STUDENT_FILE_NAME));
ois = new ObjectInputStream(fis);
studentList = (List<Student>) ois.readObject();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
closeStream(fis);
closeStream(ois);
}
return studentList;
}
/**
* close input stream
*/
private void closeStream(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* close output stream
*/
private void closeStream(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
StudentManagement class
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import javax.sql.rowset.serial.SerialException;
public class StudentManagement {
StudentDAO stdao;
List<Student> list;
Scanner sc = new Scanner(System.in);
public StudentManagement() {
try {
stdao = new StudentDAO();
list = stdao.read();
} catch (SerialException e) {
e.printStackTrace();
}
}
public void add() {
System.out.print("Enter student id \t");
int id = sc.nextInt();
System.out.println();
System.out.print("Enter student name \t");
String name = sc.next();
System.out.println();
System.out.print("Choose gender:\t[male] or [female]?");
int gender = -1;
String tempGender = sc.next();
if(tempGender.equalsIgnoreCase("male")) {
gender = 1;
}else if(tempGender.equalsIgnoreCase("female")) {
gender = 0;
}
System.out.println();
System.out.print("Enter student GPA \t");
float gpa = sc.nextFloat();
Student student = new Student(name, id, gender, gpa);
list.add(student);
stdao.write(list);
}
//View
public void showList() {
for(Student s : list) {
System.out.printf("%5d %10s %5s %10s \n");
System.out.printf("%5d %10s %5s %10s", s.getId(), s.getName(), s.isGender(), s.getGpa());
}
}
}
And this is Main class
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
StudentManagement management = new StudentManagement();
Scanner sc = new Scanner(System.in);
String choose = sc.next();
boolean quit = false;
createMenu();
while(true) {
switch(choose) {
case "1":
management.add();
break;
case "6":
management.showList();
break;
case "7":
System.out.println("QUIT");
quit = true;
break;
}
if(quit) {
break;
}
}
}
//Create menu for user's selection
public static void createMenu() {
System.out.println("----Menu----");
System.out.println("1. Add new student.");
System.out.println("2. Modify student info.");
System.out.println("3. Sort student by GPA.");
System.out.println("4. Sort student by NAME.");
System.out.println("5. Remove student.");
System.out.println("6. View.");
System.out.println("7. Exit");
}
}
Then, I end up with these errors

Reading Text file and adding the objects into an Array

I have a Contact class that basically just holds information of a contact. We store the contact object in an array.
I had to write the array into a text file, and I knew how to do that, but now I must read that file and store the objects back into an array, and I'm stuck!
Note, ContactList Below also uses class Contact, which just basically has get/set methods.
import java.util.Scanner;
import java.io.PrintWriter;
import java.io.File;
public class ContactList{
int ptr = -1;
Contact[] list;
int contactLength;
public ContactList(){//second constructor needed
list=new Contact[20];
contactLength=20;
for(int i =0;i<20;i++){
list[i]=null;
}
}
public ContactList(int length){//second constructor needed
list=new Contact[length];
contactLength=length;
for(int i =0;i<length;i++){
list[i]=null;
}
}
public boolean add(Contact c){
boolean found = false;
int i = 0;
while(!found&&i<20){
if (list[i]==null){
list[i]=c;
found=true;
ptr=i;
}
i++;
}
return found;
}
public Contact find(String name){
boolean found=false;
int i =0;
while(i<contactLength&&!found){
ptr++;
if(ptr==contactLength){
ptr=0;
}
if(list[ptr]!=null){
if (list[ptr].getName().contains(name)){
found=true;
return list[ptr];
}
}
i++;
}
return null;
}
public Contact remove(){
Contact current= list[ptr];
list[ptr]=null;
return current;
}
public void displayContacts(){
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
System.out.println(list[i].toString());
}
else {
System.out.println("Empty:");//"Name:\nAddress:\nPhone\nComments:"
}
}
}
public boolean write (String fileName){
PrintWriter p = null;
try {
p = new PrintWriter(new File(fileName));
} catch (Exception e) {
return false;
}
for(int i =0;i<contactLength;i++){
if(list[i]!=null){
p.println(list[i].toString());
}}
p.close();
return true;
}
public class Contact {
private String name;
private long phone;
private String address;
private String comments;
public void setName( String name){
this.name =name;
}
public String getName(){
return name;
}
public void setPhone(long phone){
this.phone=phone;
}
public long getPhone(){
return phone;
}
public void setAddress(String address){
this.address= address;
}
public String getAddress(){
return address;
}
public void setComments( String comments){
this.comments= comments;
}
public String getComments(){
return comments;
}
public String toString(){
return ("Name:\t\t"+name+"\nAddress:\t"+address+"\nPhone Number:\t"+phone+"\nComments:\t"+comments +"\n");
}
public Contact(String name, long phone, String address, String comments){
this.name=name;
this.phone=phone;
this.address=address;
this.comments=comments;
}
public boolean equals(Contact other){
if (this.name!=other.name){
return false;
}
if (this.phone!=other.phone){
return false;
}
if (this.address!=other.address){
return false;
}
if (this.comments!=other.comments){
return false;
}
return true;
}
Here is what I have so far...
public boolean read(String fileName){
Scanner s = null;
try {
s = new Scanner(new File(fileName));
} catch (Exception e) { // returns false if fails to find fileName
return false;
}
for(int i=0; i)
}
And YES I must use array! No lists! And nothing fancy please, this is an intro class, I won't understand it. Just scanner.
I see the pros and cons in the comment section, what about putting an end to the debate, given how you write I'm guessing you will need something like:
public static void read(String fileName){
try(BufferedReader in = new BufferedReader(new FileReader(fileName))){
String line = null;
String[] contact = new String[4];
int contactCounter = 0;
int buffer = 0;
while ((line = in.readLine()) != null){
buffer = line.split("\t").length - 1;
contact[contactCounter] = line.split("\t")[buffer];
contactCounter++;
if (contactCounter == 3){
new Contact(contact[0], contact[1], contact[2], contact[3]);
contactCounter == 0;
}
}
} catch (IOException e){
e.printStackTrace();
}
}
I strongly suggest you improve how you serialize your Contact because this format is a mess, especially having not clear boundaries, the best I could figure was counting 4 EOL to create a new Contact.
Maybe have a look at csv format: https://en.wikipedia.org/wiki/Comma-separated_values

Java - Type Mismatch: Cannot Convert From Element type String[] to List<String>

I'm unfamiliar with getters and setters (and basically just Java) but I have to use them for this assignment, so if I did anything wrong with those please tell me.
The more important issue is the error that I am getting on my method. The word for word instructions from my assignment for the particular method I'm working on are:
Your processData() method should take all the record data from your ArrayList and add the data into each of your instance fields via your setters.
But I keep getting an error that says:
Type mismatch: cannot convert from element type String[] to List
On the line that says "for (List<String> rowData: content)" on the word content.
Thank you very much for any help you can give me.
My code so far:
public abstract class Client {
String file = "bank-Detail.csv";
ArrayList<String[]> bank = new ArrayList<>();
static Client o[] = new Client[12];
public Client(String file) {
this.file = file;
}
private String ID;
private String Age;
private String Sex;
private String Region;
private String Income;
private String Married;
private String Children;
private String Car;
private String Save_Act;
private String Current_Act;
private String Mortgage;
private String Pep;
public List<String[]> readData() throws IOException {
//initialize variable
int count = 0;
//name file
String file = "bank-Detail.txt";
//make array list
List<String[]> content = new ArrayList<>();
//trycatch for exceptions
try {
//file reader
BufferedReader br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
while ((line = br.readLine()) != null) {
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
processData(content);
return content;
}
public String getID() {
return ID;
}
public void setID(String ID) {
this.ID = ID;
}
public String getAge() {
return Age;
}
public void setAge(String age) {
this.Age = age;
}
public String getSex() {
return Sex;
}
public void setSex(String sex) {
Sex = sex;
}
public String getRegion() {
return Region;
}
public void setRegion(String region) {
Region = region;
}
public String getIncome() {
return Income;
}
public void setIncome(String income) {
Income = income;
}
public String getMarried() {
return Married;
}
public void setMarried(String married) {
Married = married;
}
public String getChildren() {
return Children;
}
public void setChildren(String children) {
Children = children;
}
public String getCar() {
return Car;
}
public void setCar(String car) {
Car = car;
}
public String getSave_Act() {
return Save_Act;
}
public void setSave_Act(String save_Act) {
Save_Act = save_Act;
}
public String getCurrent_Act() {
return Current_Act;
}
public void setCurrent_Act(String current_Act) {
this.Current_Act = current_Act;
}
public String getMortgage() {
return Mortgage;
}
public void setMortgage(String mortgage) {
this.Mortgage = mortgage;
}
public String getPep() {
return Pep;
}
public void setPep(String pep) {
Pep = pep;
}
public String toString() {
return "[ID = " + ", age=";
/// ect....
}
public void processData(List<String[]> content) {
int index = 0;
for (List<String> rowData : content) {
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData.get(0));
o[index].setAge(rowData.get(1));
o[index].setRegion(rowData.get(3));
o[index].setSex(rowData.get(2));
o[index].setIncome(rowData.get(4));
o[index].setMarried(rowData.get(5));
o[index].setChildren(rowData.get(6));
o[index].setCar(rowData.get(7));
o[index].setSave_Act(rowData.get(8));
o[index].setCurrent_Act(rowData.get(9));
o[index].setMortgage(rowData.get(10));
o[index].setPep(rowData.get(11));
System.out.println(rowData);
index++;
}
}
public void printData() {
}
}
The problem is in the processData method. The type of content is List<String[]>. So when you try to loop this list, each element is a String array, not List. Also, since each element in your list is a String array, you can access the elements of each of the String Array elements of the list by using the normal array square brackets, instead of get method of List. Try the following fix:
public void processData(List<String[]> content) {
int index=0;
for (String[] rowData: content){
//initialize array of objects
//o[index] = new Client();
//use setters to populate your array of objects
o[index].setID(rowData[0]);
o[index].setAge(rowData[1]);
o[index].setRegion(rowData[3]);
o[index].setSex(rowData[2]);
o[index].setIncome(rowData[4]);
o[index].setMarried(rowData[5]);
o[index].setChildren(rowData[6]);
o[index].setCar(rowData[7]);
o[index].setSave_Act(rowData[8]);
o[index].setCurrent_Act(rowData[9]);
o[index].setMortgage(rowData[10]);
o[index].setPep(rowData[11]);
System.out.println(rowData);
index++;
}
}
As your error hints at... content is a List<String[]>, so it contains String[] elements, not List<String> elements.
If your end goal is a list of Client objects, just make the method List<Client> readData() instead.
List<Client> clients = new ArrayList<Client>();
BufferedReader br = null;
try {
//file reader
br = new BufferedReader(new FileReader(file));
//string to add lines to
String line = "";
Client c = null;
while ((line = br.readLine()) != null) {
c = new Client();
String[] rowData = line.split(",");
c.setID(rowData.get(0));
...
clients.add(c);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
try {
if (br != null) br.close();
} catch (Exception e) {}
}
return clients;

cannot write in the file [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
good day guys, im creating a program that will write the data to a text file. the data is coming from an array list, it is a data that is solved from the array list e.g :
public double getGincome(){
gincome=rpd*dwork;
return gincome;
}
the problem is i cannot write to my txt file..here is my code in writing the data:
public static boolean payrollWriteToFile(String filename) {
boolean saved = false;
PrintWriter pw = null; // pw is a PrintWriter identifier
try {
// instantiate pw as PrintWriter, FileWriter
pw = new PrintWriter(new FileWriter(filename));
try {
// for each loop. each data from payrolls is
written to parameter
for (Person payroll : payrolls) {
pw.println(payroll.getName());
pw.println(payroll.getGincome());
pw.println(payroll.getSss());
pw.println(payroll.getPagibig());
pw.println(payroll.getPhil());
pw.println(payroll.getDeduc());
pw.println(payroll.getNincome());
}
saved = true;
} finally {
pw.close();
}
} catch (IOException e) {
e.printStackTrace();
}
return saved;
}
heres my array
public class Person {
private String name;
private String add;
private String gender;
private String status;
public double rpd;
public double dwork;
public static int EmployeeCount;
public double gincome;
public double nincome;
public double deduc;
public double sss;
public double pagibig;
public double phil;
public Person(double gincome, double nincome, double deduc, double sss, double
pagibig, double phil ) {
this.gincome = gincome ;
this.nincome = nincome;
this.deduc = deduc;
this.sss = sss;
this.pagibig= pagibig;
this.phil = phil;
}
Person( String name , double gincome, double sss, double pagibig, double phil,
double deduc, double nincome){
this.gincome = gincome;
this.nincome = nincome;
this.sss = sss;
this.pagibig = pagibig;
this.phil = phil;
this.deduc = deduc;
}
Person(String name, String add, String gender, String status, double dwork, double rpd)
{
this.name = name;
this.add = add;
this.gender = gender;
this.status = status;
this.rpd = rpd;
this.dwork = dwork;
}
public double getGincome(){
gincome=rpd*dwork;
return gincome;
}
public double getDeduc(){
double sss = gincome *.03 ;
double pagibig = gincome *.02;
double philhealth = gincome* .0125 ;
deduc= sss + pagibig +philhealth;
return deduc;
}
public double getNincome(){
return nincome;
}
public double getSss(){
return sss = getGincome() * .03;
}
public double getPagibig(){
return pagibig = getGincome() * .02;
}
public double getPhil(){
return phil = getGincome() * .0125;
}
public static int getEmployeeCount(){
return EmployeeCount;
}
public String getName() {
return name;
}
public String getAdd() {
return add;
}
public String getGender() {
return gender;
}
public String getStatus() {
return status;
}
public double getRpd(){
return rpd;
}
public double getDwork(){
return dwork;
}
public void setName(String name) {
this.name = name;
}
public void setAdd(String add) {
this.add = add;
}
public void setGender(String gender) {
this.gender = gender;
}
public void setStatus(String status) {
this.status = status;
}
public void setRpd(double rpd){
this.rpd = rpd;
}
public void setdWork(double dwork){
this.dwork = dwork;
}
}
i hope you can help me guys.
Use a BufferedWriter instead, if you are allowed to (maybe you aren't for homework purposes or some other reason).
File file = new File(filename);
if (!file.exists())
{
try
{
file.createNewFile();
} catch (Exception e)
{
e.printStackTrace();
}
}
try
{
// Read to end of file for writing
BufferedReader read = new BufferedReader(new FileReader(file));
String complete = "";
String line = null;
while ((line = read.readLine()) != null)
{
complete += line + "\n";
}
// Write your data
BufferedWriter write = new BufferedWriter(new FileWriter(file));
for (Person payroll : payrolls)
{
write.append(payroll.getName());
write.append(Double.toString(payroll.getGincome()));
write.append(Double.toString(payroll.getSss()));
write.append(Double.toString(payroll.getPagibig()));
write.append(Double.toString(payroll.getPhil()));
write.append(Double.toString(payroll.getDeduc()));
write.append(Double.toString(payroll.getNincome()));
}
read.close();
write.close();
} catch (Exception e)
{
e.printStackTrace();
}
This should work if your for loop and all your getter methods are properly used.
Try pw.flush(); before pw.close(); in the finally block. It may solve the problem.
Otherwise the code looks correct to me.

Address book that reads and write from a data file

I'm doing a small program an addressbook that allows the user to: add contact, search contact and delete contact. All of this data is read and written to .dat file.
Also, how would you create a layout in the data file, (i.e. name, lastname, address and number)?
I'm terrible at Java and I need to get this done.
My code:
public interface Inter
{
//Interface class
public void addContact();
public void deleteContact();
public void searchContact();
public void readFile();
}
public class Contact
{
static String name;
static String lastName;
static String address;
static String number;
public Contact () { }
}
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader; // reads from dat file
import java.io.FileWriter; // writes from dat file
import java.io.IOException;
import java.io.InputStreamReader;
public class Phonebook extends Contact implements Inter
{
public static void main(String[] args)
{
} // main
#Override
public void deleteContact() { }
#Override
public void searchContact() { }
#Override
public void addContact()
{
String details = null;
System.out.println("Enter new contact i.e name:number:lastname ");
InputStreamReader converter = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(converter);
try
{
details=in.readLine();
String[] tokens =details.split(":"); // eg david :098:Needham
name= tokens[0];
lastName = tokens[1];
address = tokens[2];
number = tokens[3];
} catch (IOException e1) { }
FileWriter fw = null; // writes contact info to the dat file
try
{
fw = new FileWriter("data.dat");
fw.write(name);
fw.write(lastName);
fw.write(address);
fw.write(number);
} catch (IOException e) { }
BufferedWriter bw = new BufferedWriter(fw);
}
public void readFile() // reads contacts from dat file
{
try
{
BufferedReader in = new BufferedReader(new FileReader("data.dat"));
String str;
while ((str = in.readLine()) != null)
{}
} catch(Exception ex) { }
}
}
Your file format should be a .csv, so it would look like:
name,lastname,address,number,
name,lastname,address,number,
name,lastname,address,number,
I know I shouldn't be posting code for you, but here:
class Contact {
public String name, lastname, address, number;
public Contact(String name, String lastname, String address, String number) {
this.name = name;
this.lastname = lastname;
this.address = address;
this.number = number;
}
public boolean equals(Contact c) {
if(name.equals(c.name) && lastname.equals(c.lastname)
&& address.equals(c.address) && number.equals(c.number))
return true;
return false;
}
public String toString() {
return name+","+lastname+","address+","+number+",";
}
}
public class ContactDriver {
public ArrayList<Contact> contacts = new ArrayList<Contact>();
public static void addContact(Contact c) {
contacts.add(c);
}
public static Contact deleteContact(Contact c) {
return contacts.remove(c);
}
public static int searchContact(Contact c) {
for(int i = 0; i < contacts.size(); i++)
if(contacts.get(i).equals(c))
return i;
return -1;
}
public static void readContacts(String file) throws Exception {
Scanner in = new Scanner(new File(file)).useDelimiter(",");
while(in.hasNextLine()) {
addContact(in.next(), in.next(), in.next(), in.next());
}
}
public static void writeContacts(String fileName) {
FileWriter dest = new FileWriter(fileName);
for(Contact c : contacts)
dest.write(c.toString());
}
public static void main() {
readContacts();
// Do logical stuffs
writeContacts();
}
}
That code is untested, so I'll edit anything that has an error.
Have fun learning more Java!

Categories