how do I pass information from one class to another - java

I am creating a program which allows the user to input details of customers. When they have saved each customers record there is the choice to add additional information. I am having trouble getting the the name of the saved file in my append class. I need the filename so I can then save the additional information to the same file already created for the customer. How do I pass the file name from one file to another.
File FName = fileChooser.getSelectedFile();
String name = FName.getName();
public String getname() { return name; }
This code is in my customer class how do I get this information in my append class??

Possibly something like this:
Customer customer = new Customer();
// do some stuff with your customer object, including initiating the File and saving its name to a String field called name
Append append = new Append();
append.foo(customer.getName()); // passes the name of the file to the foo method of class Append
This assumes that you'll only want the name of the file in that one method (though you could save it to a field as part of method foo()). You'd need to implement a method foo(String name) in class Append.
Another option would be to pass it as a constructor of Append:
Append append = new Append(customer.getName());
append.foo();
For this, you'd need to implement a constructor Append(String name) in class Append.

There are a couple of ways to do this depending on what exactly it is you are trying to do.
Give the Append class a member variable of the Customer class
Have the Append class constructor take a parameter that would refer to a Customer, such as a String of name or a Customer object as this is Java

Your question is not entirely clear to me, but here's a problems you might run into based on your description:
What is getName() supposed to return, the name of the file, or the name of the person? If it's supposed to return the file name, then use getFileName() instead - it's clearer!
I don't really understand why you'd need an Append class. Personally, I'd handle appending additional info inside the Customer class. I'd do it so that every time a value is added or changed, the info is saved back into the file like:
class Customer {
public void setForename(String forename) {
this.forename = forename;
save();
}
public void setSurname(String surname) {
this.surname = surname;
save();
}
public void save() {
// clear file
// add new content
String fileContents = "forename="+forname+"&surname="+surname;
// save to file
}
Maybe I'm not understanding your needs correctly though...

In addition to DeadPassive's answer of associating the additional information with the Customer object:
The saving of the Customer data does not belong in the Customer Class. The logic of persisting the data belongs in a seperate layer than the code that deals with manipulating the problem domain. A controller or service class seems like a more appropriate place to put the persistance logic.

Related

How to append objects (not string type) to a existing file without overwriting the written data in the file in java?

In my java code I want to append massage objects to a file AT THE MOMENT THEY ARE BEING CREATED. When I try to append a new object it overwrites previously added data in the file. Can someone explain a method to append objects (not string type objects) one by one to a existing file without getting overwritten?
Constructor of the object:
public class savedEmail{
String email;
String subject;
String date;
public savedEmail(String email,String subject,String date){
this.email = email;
this.subject = subject;
this.date = date;
}
}
//The way which I tried to append the object to the file:
class sentEmail{
public static void save(saveEmail O) throws IOException{ObjectOutputStream op = new ObjectOutputStream(new
FileOutputStream("saved.bin",true));
op.write(0);
}
}
The way that I figured out to solve this was, putting all the objects into an ArrayList and writing that ArrayList into a file by object serialization. If you want to add a new object to it, take the saved ArrayList back by deseriazing it, then append the new object and put the ArrayList back to the file.
When you create a new ObjectOutputStream, an initial sequence of bytes, or header, is written. The Java Serialization Specification describes it:
stream:
magic version contents
So, creating a new ObjectOutputStream each time you want to append is not an option. You will need to open a single ObjectOuptutStream, and keep a reference to it.
By the way, op.write(0) (writing a zero) is not the same as op.write(O) (writing the object whose reference is in the variable whose name is the capital letter O). This is one reason O is a very poor choice for a variable name. Consider naming the method argument email instead.

How to read data from a .txt file into an ArrayList to create objects

I have designed a program that reads information(customers and courses) off of two text file documents and place them into their respective ArrayList.
For example course data looks like this:
output.format("%s;%s;%s;%.2f;%s;%s;%s;%s;%b;%d;%s\r\n","Online","Java1","Davis",125.00," 1/1/2015"," 2/1/2015"," programming"," UTA ", true,12," Jones");
Notice the name of the customer "Jones" is placed at the end of the string of data so that I know which course goes to which customer.
And customer data looks like this:
output.format("%s;%d;%s;%s;%s;%d;%d;%s\r\n","Jones",786,"Cooper","Arlington","Texas",76019,12345,"student");
Notice that the customerType is placed at the end the string of data.
The first file is called customers.txt and I use a readCustomers method, located in my test case, which reads the customers.txt file, creates customers using the data, and adds them to an ArrayList called customerList.
ArrayList<Customer> customerList = new ArrayList<Customer>();
The second file is called courses.txt and I use a readCourses method, also located in my test case) which reads the the file, creates courses using the data, and finally adds the courses to their respective/correct customer. I utilize a second ArrayList called courseList to achieve this.
ArrayList<Course> courseList = new ArrayList<Course>();
I have 7 other classes in this program: Date,Time,Customer,Course,OnLineCourse,InClassCourse,Invoice(interface).
After customers are loaded with their respective customer, a method called generateInvoice calls method createInvoice in class customer which calculates the invoice for each customer and finally printing it out to a dialog box under the headings Name, Account, and Total
My problem is that I do not know how to create new customers from the customers.txt file and add them to customerList
My attempt at readCustomers method looks like this:
public static void readCustomers()
{
Scanner input;
String sentence;
String values[];
try
{
input = new Scanner(new File("customer.txt"));
while(input.hasNext())
{
sentence = input.nextLine();
values = sentence.split(";");
for(Customer c:customerList)
{
if((c.getName().equals(values[9])))
{
customerList.add(new Customer(values[0],createAddress(values[1]),Integer.parseInt(values[2])));
}
}
}
}
// there is a catch block in my program
First of all, you have to make sure the "customer.txt" file is in the right place, if you have a FileNotFoundException...
Then several things in the code above:
When I read the example of customer line, I count 11 properties. I'm wondering what you test in if((c.getName().equals(values[9]))); it doesn't look like the name of the customer.
You are reading in a list customerList which - guessing here - contains the list of Customer with only the name set, and you want to create a list of Customer beans with the additional information found in the file.
If this is the intention,
either you need to create another list and add a new instance of Customer initialised with the properties read from the file. The function readCustomers() should return the new List<Customer>.
or you want to update the Customer bean instances that are in the customerList. But in this case, you have nothing to add to the list. You just need to get each bean instance, set the properties, and continue. At the end of the function, the customerList shall be updated.

How do I write and delete Objects from a RandomAccessFile?

I am currently working on a school project for which I need to save my data to a RandomAccessFile. I figured that this is by far not the most efficient way, but I have to do it. Note: I have to use the RandomAccessFile class.
I understand how I can save simple strings and int created in the main method to a file, but I am having trouble transferring this knowledge onto my own program.
I have 4 different classes, i.e. Database, Group, Student, Rehearsal. The Database class lets you add groups to a linked list of groups. To each group, you can then add students (see below) as well as rehearsal dates (its a theatre management program). These are added to linkedlist<Student> and linkedlist<Rehearsal> respectively.
This is my addStudent method in the Group class that adds a student to the linkedlist of a group that was created.
public void addStudent(int id, String firstname, String lastname) throws IOException {
Student newstudent = new Student(id, firstname, lastname);
if (!Students.contains(newstudent)) {
Students.add(newstudent);
} else
JOptionPane.showMessageDialog(null, "Student with ID " + id
+ " already exists in group!", "Error",
JOptionPane.WARNING_MESSAGE);
}
How do I let the method automatically write the student object to the file when it is executed?
This is my removeStudent method:
public void removeStudent(int id) {
if (!Students.remove(new Student(id, null, null))) {
JOptionPane.showMessageDialog(null, "Student with ID[" + id
+ "] not present. System unchanged.");
}
}
Pretty much the same question, how can I then delete a specific object from the file when the method is executed. If you could me help me out on that as well, that would be great :)
override the toString() method of object class in the way you want to write to the file!
then loop using foreach over the linkedlist and call toString() on student object and write to file
example:
fileOutputStream outStream=newFileOutputStream("../RandomAccessFile");//path where you want to create file
foreach(Student s in linkedlist)
{
outStream.println(s.toString()+"/n");
}
You can't delete anything from a RandomAccessFile except by implementing some file protocol that your code understands, for example filling a record with nulls, assuming your file has records, and assuming that all-nulls (or whatever) is not a legal record value. Or implement a byte header on each record such that 1 means present and 0 means deleted, or vice versa.

Dynamic variable names in Java so each new object has separate name

How can I do such a thing?
String N = jTextField0.getText();
MyClass (N) = new Myclass();
Is it even possibe?
Or as my question's explains, how can I just make a method to create a new object of my specified class just with a different name each time I call it.
I really searched everywhere with no luck.
Thanks in Advance
P.S.
I wish you guys can excuse me for not being clear enough, Just to say it as it is, I made a textfield to get the name of someone who wants to make an account, and I made a class named "Customer". and a button named "Add". Now I want every time "Add" is clicked, compiler take what is in my textfield and make an object of the class "Customer" named with what it took from the textfield
It was too hard to read it in comments so I updated my question again, so sorry.
I'm stuck so bad. I suppose my problem is that I didn't "understand" what you did and only tried to copy it. This is what I wrote:
private void AddB0MouseClicked(java.awt.event.MouseEvent evt) {
String name = NameT0.getText();
Customer instance = new Customer(Name);
Customer.customers.add(instance);
and this is my Customer class:
public class Customer{
String name;
public Customer(String name){
this.name = name;
}
public String getName(){
return name;
}
static ArrayList<Customer> customers = new ArrayList<Customer>();
Variable names must be determined at compile time, they are not even part of the generated code. So there is no way to do that.
If you want to be able to give your objects names, you can use
Map<String, MyClass> map = new HashMap<>();
Add objects to the map like this (e.g):
map.put(userInput, new MyClass());
and retrieve objects like this:
MyClass mc = map.get(userInput);
I'm not entirely sure what you mean by...
how can I just make a method to create a new object of my specified
class just with a different name each time I call it
...but if I'm interpreting you correctly, I believe what you're trying to do as make MyClass accept a constructor parameter. You can do:
public class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to create a new instance of MyClass, do:
String name = jTextField0.getText();
MyClass instance = new MyClass(name);
instance.getName(); // returns the name it was given
EDIT
Since you've added clarifications in the comments since I first answered this question, I thought I would update the answer to portray more of the functionality that you're looking for.
To keep track of the MyClass instances, you can add them to an ArrayList. ArrayList objects can be instantiated as follows:
ArrayList<MyClass> customers = new ArrayList<MyClass>();
Then for each MyClass instance you wish to add, do the following:
customers.add(instance);
Note that the ArrayList should not be reinstantiated for each instance that you wish to add; you should only instantiate the ArrayList once.

how to use same string in two java files

Sorry for my bad English and for maybe stupid question but I'm new in Java.
I need use same string in 2 java files for example:
In first java file I've got code for sending emails, I've got string set to default email:
public String mail = new String ("lala#gmail.com");
and I use this string in code for send email:
email.addTo(mail);
In second java file something like set up where can user set new email address I want to have same string, connected with string in first java file. When user put new email String mail will be change to new email address and in email.addTo(mail); will be use this new address
How can I do this?
use Shared Preferences, you can store it as key-value Pair. value being your email and key can be any unique string which you want to identify it with.
I'm a bit confused with the question, but I'll take a stab at it. Basically, you would like to have one String in a given file be used in multiple locations. This is easily done using class-level variables and making them publicly accessible.
For example, in the file:
EmailObject.java
public class EmailObject {
public static final String mail = "lala#gmail.com";
// The rest of your code
}
Another file can access this like so:
OtherObject.java
public void sendEmail() {
EmailMessage email = new EmailMessage();
email.addTo(EmailObject.mail);
}
Note the static and final modifiers on the original. This ensures that you do not need an actual instance of EmailObject to access the string and it also ensures that the string is never modified accidentally by some other object.
There are, of course, other ways to do this, but this one matches your code the most. This is also a very "Java" solution. Android has other ways to share data (as indicated by the other answer).
The simplest way that I would not recommend is to have a public static field:
class A {
public static String commonString;
}
class B {
public void methodThatUsesString () {
// Do stuff with the string
Log.d("I have the string", A.commonString);
}
}
If you have two Activities, and one starts another, you can send data through Intents.
The forementioned SharedPreferences way is a good solution too, if the email address is a persistent thing, a preference if you will, and not just data reqired for an operation.
You can keep a reference of one instance of a class in the otherone, and access it's fields through it:
class A {
public String commonString;
}
class B {
private final A instaceOfA;
public B (A instanceOfA) {
this.instanceOfA = instanceOfA;
}
public void methodThatUsesString () {
// Do stuff with the string
Log.d("I have the string", instanceOfA.commonString);
}
}
Or even use a getter or setter if performance is not an issue.
Many answers depending on how the string will be used.
If it's a constant string, one that will never change, never use final static String
public final static String AUTHOR_MAIL = "lala#gmail.com";
Then you can use it in a static way wherever you want.
email.addTo(MyClass.AUTHOR_MAIL);
If this String will be used in different Activities you can not access it directly (you can not tell if the other Activity is still alive). You have to use Persistence Mechanisms such as SharedPreferences or directly send needed data in your Intent.
If it's in a helper class inside your Activity, you can just use mObject.mail to get it.

Categories

Resources