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
Related
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 2 years ago.
I am trying to create an ArrayList that reads a .csv file, processes the data into an ArrayList, and then print the list out.
My code so far.
The BankRecords class
import java.io.*;
import java.util.*;
public class BankRecords
{
String sex, region, married, save_act, current_act, mortgage, pep;
int children;
double income;
private String id;
private int age;
public BankRecords(String gender, String area, String marriage, String SaveAccount, String CurrentAccount, String HouseBill, String pepp, int minors, double paycheck, String identification, int years)
{
this.sex = gender;
this.region = area;
this.married = marriage;
this.save_act = SaveAccount;
this.current_act = CurrentAccount;
this.mortgage = HouseBill;
this.pep = pepp;
this.children = minors;
this.income = paycheck;
this.id = identification;
this.age = years;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public String getSex()
{
return sex;
}
public void setSex(String sex)
{
this.sex = sex;
}
public String getRegion()
{
return region;
}
public void setRegion(String region)
{
this.region = region;
}
public String getMarried()
{
return married;
}
public void setMarried(String married)
{
this.married = married;
}
public String getSave_act()
{
return save_act;
}
public void setSave_act(String save_act)
{
this.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)
{
this.pep = pep;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public int getChildren()
{
return children;
}
public void setChildren(int children)
{
this.children = children;
}
public double getIncome()
{
return income;
}
public void setIncome(double income)
{
this.income = income;
}
}
The Client abstract class
import java.io.*;
import java.util.*;
public abstract class Client
{
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
static BankRecords robjs[] = new BankRecords[600];
public static void readData()
{
try
{
BufferedReader br;
String filepath = "C:\\Users\\eclipse-workspace\\Bank_Account\\src\\bank-Detail.csv";
br = new BufferedReader(new FileReader (new File(filepath)));
String line;
while ((line = br.readLine()) != null)
{
BankArray.add(Arrays.asList(line.split(",")));
}
}
catch (Exception e)
{
e.printStackTrace();
}
processData();
}
public static void processData()
{
int idx=0;
for (List<String> rowData: BankArray)
{
robjs[idx] = new BankRecords(null, null, null, null, null, null, null, idx, idx, null, idx);
robjs[idx].setId(rowData.get(0));
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
idx++;
}
printData();
}
public static void printData()
{
System.out.println("ID\tAGE\tSEX\tREGION\tINCOME\tMORTGAGE");
int final_record = 24;
for (int i = 0; i < final_record; i++)
{
System.out.println(BankArray.get(i) + "\t ");
}
}
}
The BankRecordsTest class (extends Client)
import java.util.*;
import java.io.*;
public class BankRecordsTest extends Client
{
public static void main(String args [])
{
readData();
}
}
The error
And here is the error.
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
at java.util.Arrays$ArrayList.get(Unknown Source)
at Client.processData(Client.java:33)
at Client.readData(Client.java:24)
at BankRecordsTest.main(BankRecordsTest.java:7)
I'm not sure what the index problem is. Do note that if you run the ReadData() and PrintData() functions separately, the code runs fine but the ProcessData() method causes issues.
I think your data is likely not clean and you are making assumptions about the length of your array. The error you are getting stems from this line:
robjs[idx].setAge(Integer.parseInt(rowData.get(1)));
Clearly, rowData doesn't have 2 items (or more). This is why you are getting ArrayIndexOutOfBoundsException. So you want to check where your variable was initialized. You quickly realize it comes from
for (List<String> rowData: BankArray)
So then, the following question is where BankArray gets initialized. That happens in 2 places. First of all
static ArrayList<List<String>> BankArray = new ArrayList<>(25);
You are creating an empty list. So far so good. Note that you don't need to (and therefore shouldn't) initialize with a size. Lists are not like arrays insofar as they can easily grow and you don't need to give their size upfront.
The second place is
BankArray.add(Arrays.asList(line.split(",")));
This is likely where the issue comes from. Your row variable contains the results of Arrays.asList(line.split(",")). So the size of that list depends on the number of commas in that string you are reading. If you don't have any commas, then the size will be 1 (the value of the string itself). And that's what leads me to concluding you have a data quality issue.
What you should really do is add a check in your for (List<String> rowData: BankArray) loop. If for instance, you expect 2 fields, you could write something along the lines of:
if (rowData.size()<2){
throw new Exception("hmmm there's been a kerfuffle');
}
HTH
I have an assignment where i am to create a program that manages CDs. I am using switch statement and in the first switch case I have to add a CD to the array but only if a CD with the same ID doesn't already exist in the array.
I've tried with
if (CDid != null && !CDid.equals(CDid.getCdId) {
cdArray[counter] = cd_obj;
counter++;
} else {
counter = cdArray.length-1;
System.out.println("The array is full");
}
I've also tried a for each loop before the if statement but nothing works. Either i get the nullpointer exception and/or the cd wont add to the array.
I am not allowed to have any nullpointerexceptions in the code and I am stuck on this problem for 2 days now so im hoping someone out there can help me!
Sorry for any errors ive made this is my first time posting a question on Stacksoverflow
The following code is the CD Main class
public class Cd_main {
public static void main(String[] args){
boolean running = true;
String CDid, CDgenre, CDartist, CDalbum, CDstorageSpot, CDtrackAmount,
CDstorageAmount CDprice, searchGenre, deleteCD ;
CD[] cdArray = new CD[25];
int counter = 0;
int choice;
Scanner scanner = new Scanner(System.in);
while(running){
............................
............................
choice = scanner.nextInt();
switch(choice){
case 1:
System.out.println("......");
System.out.println("............");
CDid = scanner.next();
CDgenre = scanner.next();
CDartist = scanner.next();
CDalbum = scanner.next();
CDstorageSpot= scanner.next();
CDtrackAmount= scanner.next();
CDstorageAmount = scanner.next();
CDprice = scanner.next();
CD cd_obj = new CD(CDid, CDgenre, CDartist, CDalbum,
CDstorageSpot, CDtrackAmount, CDstorageAmount, CDprice);
if(CDid.equalsIgnoreCase(CDid.getCdId())){
cdArray[counter] = cd_obj;
counter++;
}else{
counter = cdArray.length-1;
System.out.println("The array is full");
}
}
break;
```
The CD class:
```
public class CD {
public String cd_ID;
public String genre;
public String artist;
public String album;
public String storageSpot;
public String trackAmount;
public String storageAmount;
public String price;
public CD() {
}
public CD(String cd_ID, String genre, String artist, String album,
String storageSpot, String trackAmount, String storageAmount,
String price){
this.cd_ID = cd_ID;
this.genre = genre;
this.artist = artist;
this.album = album;
this.storageSpot = storageSpot;
this.trackAmount = trackAmount;
this.storageAmount = storageAmount;
this.price = price;
}
public String getCdId() {
return this.cd_ID;
}
public void setCdId(String cd_ID) {
this.cd_ID = cd_ID;
}
public String getGenre() {
return this.genre;
}
public void setGenre(String genre) {
this.genre = genre;
}
public String getArtist() {
return this.artist;
}
public void setArtist(String artist) {
this.artist = artist;
}
public String getAlbum() {
return this.album;
}
public void setAlbum(String album) {
this.album = album;
}
public String getStorageSpot() {
return this.storageSpot;
}
public void setStorageSpot(String storageSpot) {
this.storageSpot = storageSpot;
}
public String getTrackAmount() {
return this.trackAmount;
}
public void setTrackAmount(String trackAmount) {
this.trackAmount = trackAmount;
}
public String getStorageAmount() {
return this.storageAmount;
}
public void setStorageAmount(String storageAmount) {
this.storageAmount= storageAmount;
}
public String getPrice() {
return this.price;
}
public void setPrice(String price){
this.price = price;
}
}
CDid is a String, so CDid.getCdId() makes no sense at all. You need to go through your entire array to make sure the id doesn't exit.
For instance:
boolean found = false;
for (int i = 0; i < counter; ++i) {
if (cdArray[i].getCdId().equalsIgnoreCase(CDid)) {
found = true;
break;
}
}
if (found) {
System.out.println(CDid + " already exists");
} else if (counter >= cdArray.length) {
System.out.println("The array is full");
} else {
cdArray[counter] = new CD(CDid, CDgenre, CDartist, CDalbum,
CDstorageSpot, CDtrackAmount, CDstorageAmount, CDprice);
++counter;
}
Also note that you don't need to create the CD unless you know you will be able to add it in the array.
The problem is that you are reading it the wrong way, I assume. As you are dealing with strings, there is no way to separate them from each other without a delimiter, in this case, a newline. You should use Scanner.nextLine, NOT Scanner.next. Scanner.next reads only one character at a time.
Now, for the way you should check for existing ids in the array:
//For loop to check if any of the elements match the CDId. The variable exists will be
//set to true if it already exists in the array.
boolean exists = false;
if(CDId != null) {
for(int i = 0; i < cdArray.length; i++) {
if(cdArray[i] == null) continue;
if(CDId.equalsIgnoreCase(cdArray[i].getCdId())) {
exists = true;
break;
}
}
}
if(exists) {
//If the CDId already exists... (put your own code if you want, such as an error message)
} else {
//If the id doesn't exist in the array yet, add the cd_obj to the array...
boolean added = false;
for(int i = 0; i < cdArray.length; i++) {
if(cdArray[i] == null) {
cdArray[i] = cd_obj;
added = true;
break;
}
}
//if the cd_obj wasn't added to the array, notify the user.
if(!added) {
System.out.println("The array is full");
}
}
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;
I create series of objects out of Student Class and store them in a vector. I write each object in to a .ser file once it created. Then I read them back. My code is working perfectly. What I want to know is, the way I do this is correct or are there any easy and optimized ways to get this done?? And also how to replace or delete specific object in a .ser file without re-witting whole the file again.
Student Class
public class Student implements Comparable<Student>, Serializable{
private String firstName = "";
private int registrationNumber;
private int coursework1;
private int coursework2;
private int finalExam;
private double moduleMark;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getRegistrationNumber() {
return registrationNumber;
}
public void setRegistrationNumber(int registrationNumber) {
this.registrationNumber = registrationNumber;
}
public int getCoursework1() {
return coursework1;
}
public void setCoursework1(int coursework1) {
this.coursework1 = coursework1;
}
public int getCoursework2() {
return coursework2;
}
public void setCoursework2(int coursework2) {
this.coursework2 = coursework2;
}
public int getFinalExam() {
return finalExam;
}
public void setFinalExam(int finalExam) {
this.finalExam = finalExam;
}
public double getModuleMark() {
return moduleMark;
}
public void setModuleMark(double moduleMark) {
this.moduleMark = moduleMark;
}
public int compareTo(Student s){
if (this.moduleMark > s.moduleMark)
return 1;
else if (this.moduleMark == s.moduleMark)
return 0;
else
return -1;
}
}
File writing part
public static void Write(Student mm){
try
{
FileOutputStream fileOut = new FileOutputStream("info.ser",true);
ObjectOutputStream out = new ObjectOutputStream(new BufferedOutputStream(fileOut));
out.writeObject(mm);
out.close();
fileOut.close();
System.out.println("Serialized data is saved in info.ser");
}catch(IOException i)
{
//i.printStackTrace();
}
}
Reading part
public static int Read() {
int count=0;
try{
vector = new Vector<Student>();
FileInputStream saveFile = new FileInputStream("info.ser");
ObjectInputStream save;
try{
for(;;){
save = new ObjectInputStream(saveFile);
student = (Student) save.readObject();
vector.add(student);
count++;
}
}catch(EOFException e){
//e.printStackTrace();
}
saveFile.close();
}catch(Exception exc){
exc.printStackTrace();
}
return count;
}
There is no way to delete a Student object without rewriting the whole file. The reason is that you wil corrupt the header if you try to append more Student objects. Hence when you read the objects back you will get a StreamCorruptedException.
So you will have to read the objects back, delete the required object, delete the old file and write a new one.
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.