Updating Arraylist by reading from dat file - java

so part of my program does is to create a card with a name. ill then check if the name exists in my dat file.
first, what i do is i read in my dat file and stores into an arraylist. then i implement a method to check if name exists. if not, then go ahead with creation.
but the thing is, after creation, i need to update my existing arraylist as my dat file has been updated with the newly added name.
what im thinking now is to clear my existing arraylist and then reading+store it again.
but i keep running into exceptions when i introduce the clear method. Here are my tested codes:
private ArrayList<Cards> cardList;
public void readGameCards()
{
cardList = new ArrayList<Cards>();
//clearCards(this.cardList); -> not sure where to add this
try // get data from dat file and store it into arraylist
{
Scanner myScanner = new Scanner(new File("GameCards.dat"));
while (myScanner.hasNextLine())
{
//converting codes
Cards c = new Cards(//para);
cardList.add(c);
}
myScanner.close();
}
catch (FileNotFoundException fe)
{
System.out.println("...");
}
}
public void clearCards(ArrayList<Cards> cardList)
{
if (!cardList.isEmpty())
{
cardList.clear();
//cardList = new ArrayList<Cards>();
}
}
it works fine for the first run, but on second run, the newly added name is not reflected in the arraylist.

Related

How do I read files as a object or is there a better solution to this? Please see code bellow for context

So in my java class, we need to read this file and somehow converts its content into an object
import java.util.Scanner;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Calendar {
public Appointment[] appointments;
Calendar()
{
appointments = null;
}
Calendar(int capacity, String filename)
{
Appointment[] appointments = new Appointment[capacity];
//you can see that appointments is an Appointment object
readCalendarFromFile(filename);}
private void readCalendarFromFile(String fileName){
Scanner fileRead = null;
try
{
fileRead = new Scanner(new FileInputStream("appointments.txt"));
for(int r = 0; r < 30; r++)
appointments[r]= fileRead.nextLine(); ----> This is where I am getting my error from as I cannot convert String into an object. Is there a way that I can pass this
fileRead.close();
}
catch (FileNotFoundException fe)
{
fe.printStackTrace();
System.err.println("Unable to open the file " + fileName + " for reading.");
}
}
}
Is there any way that I can convert filetext into an object or do I have to do something else with it? I have to make an appointment an object so I can't change it into anything else sadly.
You have to have a class Appointment somewhere, and what you are trying to do is add an object of the type Appointment to the array appointments, based on the info you get from the text file, right?
So, you have your for loop that reads every line from the text file, and then you need to create instances of Appointment for each line.
The class Appointment has some kind of constructor, that you need to call to create a new object (read: "a new instance") from it.
Let's assume it looks like this:
public Appointment(String title, String time, String location) {
this.title = title;
this.time = time;
this.location = location;
}
Let's also assume that every line in the file appointments.txt is formatted in the following way:
<Title>, <Time>, <Location>
Which means, that you would have to parse the line that you read from the file by splitting it (the delimiter in this case would be the ",". Just do a quick research on the internet on how to split Strings in Java, it's pretty easy actually.
When you have all the bits of information in separate variables, you have to call the constructor of Appointment, to create a new appointment that you can then add to your array. Assuming that you have three Strings with the title, the time and the location of the appointment (or whatever info you have in the text file), this would look like this:
try{
fileRead = new Scanner(new FileInputStream("appointments.txt"));
int counter = 0;
while(fileRead.hasNext()) {
String lineRead = fileRead.nextLine();
// here comes the parsing of the line into three String variables
appointments[counter] = new Appointment(title, time, location);
fileRead.close();
}
} catch(FileNotFoundException ex) {
// Do some exception handling in here, or just print the stacktrace
}
The line I want you to pay the most attention to is the Line, where it says new Appointment(title, time, location). The difference between this and the code that you posted is, that here I create a new object of the type Appointment, that corresponds with the type of the array you created earlier, in the line Appointment[] appointments = new Appointment[capacity].
You tried to directly add a String to the array, although you declared an array of the type Appointment, not of the type String.
You should read up on the topic of objects in Java in general, and what constructors are, what they do and how you use them.
For example, this topic gets explained really well and exhaustive in the official Java tutorials from Oracle (the company that develops the Java Language). I linked you the specific section that talks about constructors, but I would suggest that you read at least the whole chapter and everything before it that helps you understand what they actually talk about.
Hope this helps :)

How to store multiple custom objects from an array list into json file in java?

obBelow is my Java code to write to JSON file. I'm quite new to using JSON. I have an arraylist called myAnimals and it has multiple objects of animals(sloth, cat etc.) I want to run a loop that goes through these objects and fills in the JSON file with objects storing them. The first .put is just an example of how it will go, instead of 0 I'd ideally have a reference variable like i that will loop through so I can add all. The idea is this runs every time a new object is added to the arraylist to keep the jsonfile updated. If anyone can advise me on how to do this, that would be great.
The current issue with a loop is that the file would be overwritten each time and only have one json object not many.
public void writeJson(){
JSONObject obj = new JSONObject();
obj.put("name", myAnimals.get(0).getAnimalName());
obj.put("penType", ?);
obj.put("landSpace", ?);
obj.put("waterSpace", ?);
obj.put("airSpace", ?);
try (FileWriter file = new FileWriter("animals.json")) {
file.write(obj.toJSONString());
file.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
change
try (FileWriter file = new FileWriter("animals.json")) {
to
try (FileWriter file = new FileWriter("animals.json", true)) {
adding the true boolean value will append to the end of your file instead of overwriting it. This will work for adding new ones to your file to keep it up to date.
However you need to consider the case where a user erases an animal from your list. In that case, loop the entire arraylist of animals and overwrite whatever is in your animals.json file at that time.

How To Read and Load an Array?

I have provided the background info:
So we have are working on a project of creating Facebook Lite. And in it we have this array profiles[idx]; idx is the index number, nop is the number of profiles. There is a switch case for choosing options from the menu; the professor wants us that, when the user exits the program, it should save their profiles (profile consists of first name, last name, friends, age) and when the program loads, the code should be able to load all the profiles. It's complicated.
Here's my read/write code which doesn't seem to work. First, it just makes a file which has stuff like "Profile#21bcffb5" this written. Instead of First Name:, Last Name: etc (elements inside the array). Also it doesn't load the profiles and my program gets stuck in an endless loop.
public void write()
{
try{
PrintStream writer = new PrintStream( new File("ProfileData.txt"));
for (int i=0; i<nop; i++){
writer.println(profiles[idx]);
}
writer.close();
}
catch(IOException e){
System.out.println(e);
}
}
public void read()
{
try {
Scanner s = new Scanner ( new File("ProfileData.txt"));
while(nop>0){
System.out.println(profiles[idx]);
}
}
catch(IOException e){
System.out.println(e);
}
}
It is printing the memory location at which Profile object is stored accessed by profiles[idx]. You should implement toString() method in Profile class which will print all the properties of the object

Loading information from file in different ways

My program currently has this working:
Bank bank = new Bank();
bank.openAccount(new CheckingAccount(10100, new Customer("First", "Last"),500.00,false));
bank.openAccount(new CheckingAccount(10101, new Customer("First", "Last"),2000.00,true));
bank.openAccount(new SavingsAccount(2010, new Customer("First", "Last"),5000.00,0.02));
Now I am trying to load this information from a file instead, but I ran into a bit of a wall. I want the new Customer information to include both the first and last name which are stored in separate index positions as separate variables, but while this will work:
new Customer[FIRST_INDEX],
I can't seem to get it to accept two index positions without creating a new Customer again. This is turn is causing issue with the method in Accounts where I'd like to keep the same format. How can I go about doing this?
public CheckingAccount(int accountNumber, Customer owner, double currentBalance, boolean freeChecks)
{
super(accountNumber, owner, currentBalance);
this.freeChecks = freeChecks;
}
Another problem I am running into is that the last index position can be one of two variables depending on if I am dealing with a checking account or a savings account:
private final static int FREE_CHECKS_INDEX = 4; // This loads a boolean
private final static int INTEREST_INDEX = 4; // This loads a double
Given this, I'm not entirely sure if my above approach would even work at all. The program is supposed to load either a Checking Account or Savings Account object, but since both types of accounts are stored in the same file I am wondering if I could read the last index position of each line of the text file before creating the object, but I'm not really sure how to go about doing that.
To be clear, I have this problem working perfectly without loading the data from the file, I am just unsure about the best approach for adapting it without having to rewrite all my other classes. Here's the new thing I am trying to do which I know isn't right:
protected static void loadAccountInformationFromFile() throws Exception
{
try ( Scanner fin = new Scanner(new File(INPUT_CUSTOMER_FILE)) )
{
String record;
String[] fields;
while ( fin.hasNext() )
{
record = fin.nextLine();
fields = record.split(",");
Bank bank = new Bank();
bank.openAccount
(
new CheckingAccount(Integer.parseInt(accountNumber[ACCOUNT_NUMBER_INDEX]),
new Customer[FIRST_INDEX, LAST_INDEX],
currentBalance[BALANCE_INDEX],
freeChecks[FREE_CHECKS_INDEX]
)
);
}
} catch (Exception e)
{
throw e;
} // end try
}

adding item to store in swing java using submit button

I created a store that saves records of person instances.
when adding the employees from CLI it works and the store increments, when using swing and CLI for debug i can see the new record but the increment is not done !
submit.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
Store recordStore;
recordStore = new Store(1);
// here add the submitting text
Employee em = new Employee("mn",'M', new Date(18,12,1991), "025", new Date(2,5,2009));
if (!Store.isFull())
{
recordStore.add(em);
recordStore.displayAll();
System.out.println("Current size of store is " + Store.getCount());
}
else
{ JOptionPane.showMessageDialog(null, "The store seems to be full, please save it, and create a new one!"); }
The store add function
public void add(Person p)
{
// person p is added to array
list[count++] = p;
}
I suspect that your problem is that you're creating a new Store instance each time the ActionListener code is run. Perhaps you want to create a Store instance once in the class and add to it in the ActionListener.
public void add(Person p)
{
// person p is added to array
list[count++] = p;
}
If above function is defined in the Store class then you are initializing a new instance
Store recordStore;
recordStore = new Store(1);
every time. So your list count will always be 1. So as Hovercraft Full Of Eels has suggested
move that outside the ActionListener class and change code accordingly.
Or else use a static count that stores the count of records of person instances that you have added.

Categories

Resources