Store array of objects into text file in Java - java

I need help with saving an array to a text file. So I have the following array
private Passenger[] queueArray = new Passenger[30];
and this is the class that I have
public class Passenger
{
private String firstName;
private String surname;
private int secondsInQueue;
Passenger(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
secondsInQueue = 0;
}
public String getName()
{
return firstName + " " + surname;
}
public void setName(String firstName, String surname)
{
this.firstName = firstName;
this.surname = surname;
}
public Integer geSeconds()
{
return secondsInQueue;
}
public void setSecondsInQueue(Integer SecondsInQueue)
{
this.secondsInQueue = SecondsInQueue;
}
public void display()
{
System.out.println(firstName + " " + surname + " " + secondsInQueue);
}
}
I need to save the first name and the surname of the passengers to a text file. And then I need to read the file back to the array.
I am literally so stuck... Any help would be appreciated.
Thank You!

Change the class implementation as below, to support java serialization. No methods to implement, it is a marker interface.
import java.io.*;
public class Passenger implements Serializable {}
Then you can write the objects in to any file with any extension. Then using java deserialization you can read the object array and iterate it through. Refer to this article, it has a simple example https://www.javatpoint.com/serialization-in-java.
At the time you de-serialize the object, you can call the getter method for the array object and iterate it through.
ObjectInputStream in=new ObjectInputStream(new FileInputStream("f.txt"));
YourClass s=(YourClass)in.readObject();
Passenger[] pasngrArray = s.getPassengerArray(); // call a method to get the array
for (Passenger p : pasngrArray){
// your code to access the two properties here.
}

Related

Cannot resolve symbol in Java. I want to run the code of second class in the first class

I am learning Java from tutorials, and recently I faced with one problem. I need to create several classes, and I need to read all that classes through first class. Already I passed that tutorial where I understood everything and tried that thing. But now I want to create a real world app on Java, I did the exact thing which was showing in tutorial, but I am getting that error. Please, correct me where I have mistaken
Code of first class:
package com.company;
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
System.out.println(em);
}// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
}
Second one:
package com.company;
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
}
}
Screenshotes:
Thanks
You can use System.out.println(this) in constructor. It means that you will print created instance to console. And also don't forget to override toString() method - because if you don't override it, you will get object's name with hashcode.
Hope this code will help you to reach the goal:
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
System.out.println(this);
}
// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
#Override
public String toString() {
return "Email{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Another solution. Just override toString of Email class. And put printing of em to main method.
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String alternateEmail;
private int capacityMailbox;
// Constructor to recieve the first name and last name
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
// Ask for the department
// Generate a random password
// Set the mailbox capacity
// Set the alternate email
// Change the password
#Override
public String toString() {
return "Email{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
'}';
}
}
Main class:
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
System.out.println(em);
}
}
The constructor of your Email Class does not have a variable called em.
You should put System.out.println(em) into the Main method of your EmailApp class.
The object reference "em" has no scope in first class i.e. class Email.
make these following two changes and compare your code. you will understand where you went wrong.
//-----------------------------------------------------change 1
public Email(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
and in second class:
//---------------------------------------------change 2
public class EmailApp {
public static void main(String[] args) {
// write your code here
Email em = new Email("John", "Smith");
System.out.println(em.firstname);
System.out.println(em.lastname);
}
}
and make all member variables public for now. You will make it private when you understand "getters and setters" concept.

Getters in Java for novice java users

Getters and setters are used to implement two of the fundamental aspects of Object Oriented Programming which are
Abstraction
Encapsulation
Suppose we have an Employee class:
package com.highmark.productConfig.types;
public class Employee {
private String firstName;
private String middleName;
private String lastName;
public void getFirstName(){
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
// Similarly for lastName
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
}
UPDATE : Is this usage right with the workerclass?
public class getNames() {
private String firstName;
private String middleName;
private String lastName;
//Constructor
public String getNames() {
Scanner input = new Scanner();
// output message to insert name part
String firstName = input.ReadLine();
String middleName = input.ReadLine();
String lastName = input.ReadLine();
Employee emp = new Employee();
emp.setFirstName(firstName);
emp.setMiddleName(middleName);
emp.setLastName(lastName);
}
}
Please try to explain the flaw in understanding if any.
Yes, you are correct on one thing for sure. Getters are Setters are a way to ensure the principle of Encapsulation in Object Oriented Programming languages like Java.
When you have a private member in your class, then its scope gets restricted to that particular class itself, but you may want to provide getters and/or setters to make that member accessible to classes outside your class.
Suppose you have a member like this,
private String firstName;
then this is your getter for this member,
public String getFullName(){
return this.getFirstName() + this.getMiddleName() + this.getLastName();
}
but this is not,
public String getFirstName() {
Scanner user_input = new Scanner(System.in);
firstName = user_input.next( );
return firstName;
}
because "getter" is just a term used to get the value of a member which is private. The sole purpose of a getter method is just to get the original value of a member.
In the latter method, the purpose is absolutely different. You are trying to get the first name as input, so technically it cannot be called a "getter" in any way.
Hope this clears your doubt.

Loading a moviedatabase txt file in Java and sorting it

The goal of this project is to read a movie data base txt file, where each line in the file contains the name, year released, and associated actors for one movie. Each piece of information is separated by ‘/’ characters. The year is specified inside parentheses at the end of the movie name. I have already created an actor class, which stores a String firstname and a String lastname, and a movie class which holds all the above info about the movie. In the movieDataBase class, I need to load the .txt file, and split it in to the different components. I understand how to split the file in to different elements, I just don't know how to turn the string of associated actors into and arrayList of Actor objects. Sorry for the newbie question. My java book doesn't talk about it at all and I have been looking for the past 3 hours on the internet! Here's my code:
public class Actor {
private String firstName;
private String lastName;
public Actor(){
firstName = "";
lastName = "";
}
public Actor( String first){
this (first, "");
}
public Actor( String first, String last){
firstName = first;
lastName = last;
}
public String getFirstName(){
return firstName;
}
public void setFirstName( String first){
firstName = first;
}
public String getLastName(){
return lastName;
}
public void setLastName( String last){
lastName = last;
}
public String toString(){
return firstName + " " + lastName;
}
}
//new class
public class MovieDatabase
public void loadDataFromFile( String aFileName) throws FileNotFoundException{
//creating a scanner to read the file
Scanner theScanner = new Scanner(aFileName);
theScanner = new Scanner(new FileInputStream("cast-mpaa.txt"));
while(theScanner.hasNextLine()){
String line = theScanner.nextLine();
String[] splitting = line.split("/");
String movieTitle = splitting[0];
filmActors.add(splitting[2]);
//this is where I have issues
ArrayList<Actor> associatedActors = new ArrayList<Actor>();
for( String newActors : filmActors){
}
}
}
}
You could do something like:
for( String newActor : filmActors){
associatedActors.add(new Actor(newActor));
}
This means with new Actor you are creating a new object instance of Actor and adding it to the array List that you created.
To Actor class, you are passing the actor name in constructor and that's how you are constructing the Actor object i assume.

Error while trying to print out arraylist

The error I am reviving is "void type is not allowed here " how would I fix this error in order to print out my array list.
import java.util.ArrayList;
public class Library
{
private ArrayList<Member>listOfMembers;
public Library()
{
listOfMembers = new ArrayList<Member>();
}
public void storeMember(Member Member)
{
listOfMembers.add(Member);
}
public int numberOfMembers()
{
return listOfMembers.size();
}
public void listMembers()
{
for (int item=0; item<listOfMembers.size(); item++ ) {
Member m = listOfMembers.get (item);
System.out.println(m.GetWholeName());
}
}
}
and here is my member class just in case you need it
class Member
{
// The fields.
private String firstname;
private String lastname;
private Integer number;
private Integer id;
/**
hehe
*/
public Member(String firstName, String lastName, Integer telNumber, Integer memberId)
{
firstname = firstName;
lastname = lastName;
number = telNumber;
id = memberId;
}
// Add the methods here ...
public void GetWholeName(){
System.out.println(firstname + (" ") + lastname);
}
}
I'm trying to print the first and last name of my member class by using an array list in my library class
You are trying to print out the result of m.GetWholeName() which returns void. Change GetWholeName to return a String instead, or simply call GetWholeName as it's already printing the name to standard out although that behavior doesn't quite match up to the behavior the name would imply.
public String GetWholeName() {
return firstname + " " + lastname;
}
In Member class change this:
System.out.println(firstname + (" ") + lastname);
to this:
return firstname + " " + lastname;

Creating a class with different argument lengths

How do I create a class that has different lengths of arguments?
public static void main(String[] args) {
group g1 = new group("Redskins");
group g2 = new group("Zack", "Mills", 21);
group g3 = new group("John","Smith",20);
group g4 = new group("Fred","Fonsi",44);
group g5 = new group("Jeb","Bush",26);
System.out.println(g1.getName());
}
}
I want to be able to display the team name (redskins) and then each member after that using one method.
I've tried using two methods and got that to work, but can't get one.
I was thinking about possibly using an array but not sure if that would work.
Thanks for any help.
I have three classes the main, student, and group.
I need the group class to display the group name and then figure out how to display the students information underneath. The only thing, is that my assignment is vague about whether I can use two methods or one.
public class student {
String firstName;
String lastName;
int age;
student(String informedFirstName, String informedLastName, int informedAge){
firstName = informedFirstName;
lastName = informedLastName;
age = informedAge;
}
String getName()
{
return "Name = " + firstName + " " + lastName + ", " + "Age = " + age;
}
}
public class Team{
String name;
Set<Player> players;
public Team(String name){
this.name = name;
}
public void addPlayer(Player p){
players.add(p);
}
}
public class Player{
String name;
etc
}
EDIT for revised question:
Ok, Im going to show a lot here. Heres what a proper Java versio of what you want for student.
public class Student {
private String firstName;
private String lastName;
private int age;
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
/*
* Use:
* Student s = new Student(Bill, Nye, 57);
* System.out.println(s.toString());
*/
#Override
public String toString() {
return "First Name: " + firstName + ", Last Name: " + lastName + ", Age: " + age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The Things to take away from this.
1) Capitalize the first letter of class names! (Student)
2) note the class variables are private (look here for a tutorial Java Class Accessibility) and have getters and setter to control access outside the class.
3) I dont say "getName()" and return name and age. This doesnt make sense. Instead i make it so when you go toString() it shows all the relevant information.
4) Java is an object oriented language which means the classes that model data are supposed (to some extent) model appropriately to the way they are used in real life. This makes it more intuitive to people reading your code.
5) if your Group class (note the capital!) needs to contain many Students use a LIST such as an ArrayList. Arrays would make no sense because you dont know how many Students are going to be in each Group. A SET like i used above is similar to a list but only allows ONE of each item. For simplicity use a list though
6) the THIS operator refers to class (object) variables. In the constructor this.firstName refers to the firstName within the Class (object...an instance of the class) whereas just firstName would refer to the variable in the contructor and not alter the class variable.
use the constructor for that
class group {
String fname,lname;
group(String fname ){
this.fname=fname;
}
group(String fname,String lname){
this.fname=fname;
this.lname=lname;
}
group(String fname,String lname,int age){
this.fname=fname;
this.lname=lname;
this.age=age;
}
public String getName(){
return fname+lname+age;
}
}

Categories

Resources