a simple one:
I am trying to use a constructor to create objects, but my objects are created empty. The constructor lives in a different class within the same package.
public static void main(String[] args) {
//Initialize all data:
ArrayList<Airport_example> all_airports = new ArrayList<Airport_example>();
Airport_example perth = new Airport_example("01","Perth","PER","Australia","WST");
Airport_example brisbane = new Airport_example("02","Brisbane","BNE","Australia","EST");
//Add airports to ArrayList
all_airports.add(perth);
all_airports.add(brisbane);
//debugging
System.out.println(all_airports);
}
The constructor in a separate class looks like this:
public class Airport_example extends HashMap<String,String> {
//list of variables
private String airportID;
private String city;
private String code3;
private String country;
private String timezone;
// constructor to initialize objects
public Airport_example(String airportID, String city, String code3, String country, String timezone) {
// Constructor variable initialization
this.airportID = airportID;
this.city = city;
this.code3 = code3;
this.country = country;
this.timezone = timezone;
}
}
The System.out.println statement returns an empty array. Have I missed a simple trick here?
[{}, {}]
Your constructor works fine; the problem is that you are extending a HashMap and expecting it to know the contents of the private fields of the Airport_example subclass. To have your print statements work as you intend them to, you have to override the toString method.
I would recommend changing your code to the following:
public class Airport_example {
private String airportID;
private String city;
private String code3;
private String country;
private String timezone;
public Airport_example(String airportID, String city, String code3, String country, String timezone) {
this.airportID = airportID;
this.city = city;
this.code3 = code3;
this.country = country;
this.timezone = timezone;
}
}
public String toString() {
// replace the string you want each object to print out
return this.airportID + ", " + this.city + ", " + this.code3 + ", " + this.country + ", " + this.timezone;
}
The reason it's printing an empty array is that it's currently calling HashMap's toString, and, as you don't define any of the HashMap fields, it's treating it as an empty HashMap.
Related
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.
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.
}
public void body()
String name = "", address = "",checkin = "", checkout = "";
InputStreamReader read = new InputStreamReader(System.in);
BufferedReader in = new BufferedReader(read);
for(k =1;;k++)
{
}
I need to store whole method in a array variable at once.
well actually for every loop i want to create a element in array.
Like chrylis said in his comment you could create a class Reservation with the fields you want to store.
public class Reservation {
private String name;
private String address;
private String checkin;
private String checkout;
public Reservation(String name, String address, String checkin, String checkout) {
this.name = name;
this.address = address;
this.checkin = checkin;
this.checkout = checkout;
}
//getters and setters ...
}
Then you can create a new Object of it in your method and add it to your array
ArrayList<Reservation> reservations = new ArrayList<>();
for(k =1;;k++) {
reservations.add(new Reservation(...));
}
I used an ArrayList instead of an Array because you can add as many elements as you want to an 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;
Error says something about eZip not being recognized or something
public class Address
{
private String name;
private String street;
private String city;
private String state;
private String zip;
public Address(String aName, String aStreet,
String aCity, String aState, String aZip)
{
name = aName;
street = aStreet;
city = aCity;
state = aState;
zip = eZip;
}
}
um, perhaps it is because the parameter you gave is called aZip and eZip is not something you've made anywhere else I'm assuming.
You're declaring the constructor parameter
...String **aZip**)
And then referencing at the bottom of your constructor
zip = **eZip**;
You just misstyped, that's all.