Im trying to call the method show in the klub class, from my demo class, and to call the method visAlleAtleter in the demo class (from my klub class), but I get an error saying it can't find the symbol and then the name of the method. I have tried to specify where I want it from, but I'm not certain how to do it. This is my Klub class
import java.util.ArrayList;
public class Klub {
private String navn;
private ArrayList<Atlet> atleter;
public Klub(String navn) {
this.navn = navn;
atleter = new ArrayList<>();
}
public void addAtlet(Atlet atlet) {
atleter.add(atlet);
}
public void visAlleAtleter() {
System.out.println(navn);
for(Atlet atlet: atleter) {
atlet.display();
}
}
public void visAlleAtleter2(boolean samletValue) {
if(samletValue = true) {
Atlet.show();
} else {
}
}
}
this is my Demo class
public class Demo {
public static void main(String[] args) {
Klub minKlub = new Klub("SWU United");
Atlet atlet1 = new Atlet("Pan", "Tennis", 43.5, 21);
Atlet atlet2 = new Atlet("Peter", "Golf", 41.5, 29);
Atlet atlet3 = new Atlet("Robby", "Tennis", 43.5, 20);
Atlet atlet4 = new Atlet("Niklas Klein", "Maisball", 21.2, 23);
Atlet atlet5 = new Atlet("Linni Maister", "Maisball", 44.1, 32);
Atlet atlet6 = new Atlet("Dennis Michael", "Maisball", 32.5, 11);
minKlub.addAtlet(atlet1);
minKlub.addAtlet(atlet2);
minKlub.addAtlet(atlet3);
minKlub.addAtlet(atlet4);
minKlub.addAtlet(atlet5);
minKlub.addAtlet(atlet6);
Klub.visAlleAtleter();
}
}
and my atlet class
public class Atlet {
private String navn;
private String sportsgren;
private double pris;
private int alder;
public Atlet(String navn, String sportsgren, double pris, int alder) {
this.navn = navn;
this.sportsgren = sportsgren;
this.pris = pris;
this.alder = alder;
}
public void oppdaterPris(double nyPris) {
pris = nyPris;
}
public double getPris() {
return pris;
}
public double predSalgspris() {
return pris-0.95*Math.abs(25-alder);
}
public void display() {
System.out.println(navn + " (" + alder + ") - " +
sportsgren + ": " + pris + "kr (" + predSalgspris() + "kr)");
}
}
Method visAlleAtleter is not static so your can't call it as you do Klub.visAlleAtleter().
Just call method on object minKlub.visAlleAtleter().
The problem lies in the line Klub.visAlleAtleter(); in the main method in Demo. To correct this you have to replace it with minKlub.visAlleAtleter();.
The reason for this is that according to your code, you have an instance of the class Klub called minKlub. The method visAlleAtleter() is bound to any instance of the class Klub, not the class Klub itself.
EDIT:
To illustrate why your attempt could be an issue, consider this example:
public class Demo {
public static void main(String[] args) {
Klub minKlub = new Klub("SWU United");
Klub dinKlub = new Klub("SEU United")
Atlet atlet1 = new Atlet("Pan", "Tennis", 43.5, 21);
Atlet atlet2 = new Atlet("Peter", "Golf", 41.5, 29);
minKlub.addAtlet(atlet1);
minKlub.addAtlet(atlet2);
Atlet atlet3 = new Atlet("Mads", "Fotball", 123, 123);
Atlet atlet4 = new Atlet("Mikkelsen", "Curling", 123, 123);
dinKlub.addAtlet(atlet3);
dinKlub.addAtlet(atlet4);
Klub.visAlleAtleter();
}
}
In this example, when calling Klub.visAlleAtleter(), it is impossible to know whether Java should call the method on minKlubb or dinKlubb. Its important that you see minKlub and dinKlub as physical instances of the Klub class.
Coincidentally, writing Klub.someArbitraryMethod() is actually a commonly used feature in java, where someArbitraryMethod() is statically declared. This way of writing is only possible if you declare the method as static:
public static void someArbitraryMethod() {...}
This means that the method doesn't belong to any physical instances of the class Klub, but rather it belongs to the class Klub itself. Doing
minKlubb.someArbitraryMethod();
will therefor cause a compilation error.
Related
In this application we have the Automovel class:
public class Automovel {
private String marca;
private String matricula;
private String anoConstrucao;
private Motor motor;
private int preco = 0;
}
(with their builders, getters and setters) and there is a class called Motor that is an attribute of the Automovel class.
Motor Class:
private int potencia;
public Motor() {}
public Motor(int potencia){
this.potencia = potencia;
}
public int getPotencia() {return this.potencia;}
public void setPotencia(int potencia) {
this.potencia = potencia
}
There are also 2 subclasses of this class (MotorEletrico and MotorCombustao):
Motor Elétrico:
public class MotorEletrico extends Motor {
private int autonomia;
public MotorEletrico() {}
public MotorEletrico(int potencia, int autonomia) {
super(potencia);
this.autonomia = autonomia;
}
public int getAutonomia() {
return autonomia;
}
public void setAutonomia(int autonomia) {
this.autonomia = autonomia;
}
}
Motor Combustão:
public class MotorCombustao extends Motor{
private int cilindrada;
private String combustivel;
public MotorCombustao(){}
public MotorCombustao(int potencia, int cilindrada, String combustivel){
super(potencia);
this.cilindrada = cilindrada;
this.combustivel = combustivel;
}
public int getCilindrada(){
return cilindrada;
}
public void setCilindrada(int cilindrada){
this.cilindrada = cilindrada;
}
public String getCombustivel(){
return combustivel;
}
public void setCombustivel(String combustivel){
this.combustivel = combustivel;
}
}
I store a car with an X engine in an array of Automovel objects, but when I try to access the getters and setters of the subclass (MotorCombustao / MotorEletrico), only the gets and sets of the mother class (Motor) appears. My problem is that I can't access the getters and setters of the motor subclasses.
Here's an example of what I tried:
Automovel arrayteste[] = new Automovel[49];
Motor motor1 = new MotorEletrico();
motor1.setPotencia(5);
Automovel automovel1 = new Automovel("Opel", "xx-12-xx", "2000", motor1, 2000);
arrayteste[0] = automovel1;
System.out.println(arrayteste[0].getMotor().getPotencia()); //Here, I can't Do .getAutonomia
Short answer
You need to cast
System.out.println(((MotorElettrico)(arrayteste[0].getMotor())).getAutonomia());
TL;DR
When you wrote
Motor motor1 = new MotorElettrico();
you are using polymorphism.
This is very useful when, for example you, have a list of Motor that contains more then one motor type and for all of this you want to print the potencia.
Then you can write something like this:
List<Motor> list = Arrays.asList(new MotorElectico(), new MotorCombustao());
// ----- some set
print(list);
where print method is something like this:
public void print(List<Motor> list){
for(Motor m : list){
System.out.println(String.format("Potencia %d", m.getPotencia()));
}
}
This happens because a MotorElectico IS A Motor and upcasting (casting to supertype) is always allowed.
In your case, you have to do downcasting: you are telling to a compilator that arraytest[0].getMotor() contains a Motor but this Motor is actually a MotorElectrico: you are asking to compilator to trust you. If at compile-time arraytest[0].getMotor() should not be a MotorElectrico you'd get a ClassCastException.
You need to cast the reference of the parent class to the corresponding child class if you want to access a method which is not inherited from the parent class e.g. the method, getAutonomia() is not inherited from Motor and therefore, you need to cast the reference of Motor to MotorEletrico before you can access getAutonomia(). Some more useful code is given below:
public class Main {
public static void main(String[] args) {
Automovel arrayteste[] = new Automovel[2];
Motor motor;
motor = new MotorEletrico(5, 10);
arrayteste[0] = new Automovel("Opel", "xx-12-xx", "2000", motor, 2000);
motor = new MotorCombustao(7, 4, "xx-yy-zz");
arrayteste[1] = new Automovel("Opel", "xx-08-xx", "1995", motor, 1995);
for (Automovel automovel : arrayteste) {
motor = automovel.getMotor();
if (motor instanceof MotorEletrico) {
System.out.println(((MotorEletrico) motor).getAutonomia());
}
if (automovel.getMotor() instanceof MotorCombustao) {
System.out.println(((MotorCombustao) motor).getCilindrada());
System.out.println(((MotorCombustao) motor).getCombustivel());
}
}
}
}
Output:
10
4
xx-yy-zz
[Update: the following update is based on your comment]
Another way to iterate arrayteste is as given below:
for (int i = 0; i < arrayteste.length; i++) {
if (arrayteste[i] != null) {
motor = arrayteste[i].getMotor();
if (motor instanceof MotorEletrico) {
System.out.println(((MotorEletrico) motor).getAutonomia());
}
if (arrayteste[i].getMotor() instanceof MotorCombustao) {
System.out.println(((MotorCombustao) motor).getCilindrada());
System.out.println(((MotorCombustao) motor).getCombustivel());
}
}
}
You are familiar with the Liskov substitution principle, I assume.
If you don't know the type of motor, you can write a statement that asks each instance of the Automovel array arraytest[i] what class it is.
For example:
List<Automovel> arrayteste = new ArrayList<>();
Motor motor1 = new MotorEletrico();
motor1.setPotencia(5);
Automovel automovel1 = new Automovel("Opel", "xx-12-xx", "2000", motor1, 2000);
arrayteste.add(automovel1);
Motor motor = new Motor();
String motorClass;
String[] motorTypes = {"MotorEletrico", "MotorCombustao"};
Set<String> motorClasses = new HashSet<>(Arrays.asList(motorTypes));
for (int i = 0; i < arrayteste.size(); i++)
{
motorClass = arrayteste.get(i).getMotor().getClass().getName();
if (motorClasses.contains(motorClass))
{
if (motorClass.equals("MotorEletrico"))
{
motor = (MotorEletrico)(arrayteste.get(i).getMotor());
}
else if (motorClass.equals("MotorCombustao"))
{
motor = (MotorCombustao)(arrayteste.get(i).getMotor());
}
System.out.println("Automovel #" + i + " : " + motor.getPotencia());
}
else
{
System.out.println("Não sei que classe de motor é esse . . .");
}
}
}
But it might be better to explore the class design more closely.
Possibly try to use interfaces.
I've just started to learn Java a month or so ago, and now have a problem with "non-static variable studentList cannot be referenced from a static context". I'm trying to have a separate method from main to populate the list of students, instead of copy pasting stuff from addStudent for each student; but I cannot get the methods to write to the ArrayList. (Error:(14, 27) java: non-static variable studentList cannot be referenced from a static context). I understand how the array is not static because it has an undefined size, but how could I make it work as is? Is there any better approach? Could I have the array be part of the main method and then have it passed on to addStudent, if so how?
import java.util.ArrayList;
public class Main {
ArrayList<Student> studentList = new ArrayList<>();
public static void main(String []args) {
addStudent("Adam", "Goldsmith", 70, 50);
addStudent("John", "Smith", 20, 40);
addStudent("Lewis", "Peterson", 90, 85);
for (Student obj: studentList){
System.out.println("Name: " + obj.studentForename + " "+ obj.studentSurname);
}
}
public static void addStudent(String forename, String surname, int coursework, int test) {
Student newStudent = new Student(forename, surname);
newStudent.setForename(forename);
newStudent.setSurname(surname);
newStudent.averageMark(70, 65);
studentList.add(newStudent);
}
}
and my "Student" Class:
public class Student {
String studentForename;
String studentSurname;
public Student(String studentForename, String studentSurname) {
setForename(studentForename);
setSurname(studentSurname);
}
// Set forename.
public void setForename(String newForename) {studentForename = newForename;}
// Set surname.
public void setSurname(String newSurname) {studentSurname = newSurname;}
//
public double averageMark(int courseworkMark, int testMark){
return (courseworkMark+testMark)/2;
}
// Grab the forename
public String grabForename(){
return studentForename;
}
// Grab the surname
public String grabSurname(){
return studentSurname;
}
// Grab the full name
public String grabFullName(){
return studentForename + "" + studentSurname;
}
}
Your code should look like this, especially your Student class using java encapsulation
public class Student {
private String studentForename;
private String studentSurname;
private int courseworkMark;
private int testMark;
public Student(String studentForename, String studentSurname, int courseworkMark, int testMark) {
this.studentForename = studentForename;
this.studentSurname = studentSurname;
this.courseworkMark = courseworkMark;
this.testMark = testMark;
}
public void setStudentForename(String studentForename) {
this.studentForename = studentForename;
}
public String getStudentSurname() {
return studentSurname;
}
public void setStudentSurname(String studentSurname) {
this.studentSurname = studentSurname;
}
public String getStudentForename() {
return studentForename;
}
public double averageMark(){
return (this.courseworkMark + this.testMark)/2;
}
public String grabFullName(){
return studentForename + " " + studentSurname;
}
}
And then testing via your Main class :
public class Main {
public static void main(String []args) {
ArrayList<Student> studentList = new ArrayList<>();
studentList.add(new Student("Adam", "Goldsmith", 70, 50));
studentList.add(new Student("John", "Smith", 20, 40));
studentList.add(new Student("Lewis", "Peterson", 90, 85));
for (Student obj: studentList){
System.out.println("Name: " + obj.getStudentForename() + " "+ obj.getStudentSurname());
}
}
}
import java.util.ArrayList;
public class Main {
static ArrayList<Student> studentList = new ArrayList<>();
public static void main(String []args) {
addStudent("Adam", "Goldsmith", 70, 50);
addStudent("John", "Smith", 20, 40);
addStudent("Lewis", "Peterson", 90, 85);
for (Student obj: studentList){
System.out.println("Name: " + obj.studentForename + " "+ obj.studentSurname);
}
}
public static void addStudent(String forename, String surname, int coursework, int test) {
Student newStudent = new Student(forename, surname);
newStudent.setForename(forename);
newStudent.setSurname(surname);
newStudent.averageMark(70, 65);
studentList.add(newStudent);
}
}
It was not due to undefined size but was because you were trying to access it without creating an object from a static method.
So just write static before it and it will work.
thought the above answer answers you question, but few words about static vs non static modifiyers in java
Characteristics of Static methods
A static method is called using the class (className.methodName) as opposed to to an instance reference (new instanceOfClass = class; instanceOfClass.methodName.)
Static methods can’t use non-static instance variables: a static method can’t refer to any instance variables of the class. The static method doesn’t know which instance’s variable value to use.
Static methods can’t call non-static methods: non-static methods usually use instance variable state to affect their behaviour. Static methods can’t see instance variable state, so if you try to call a non-static method from a static method the compiler will complaint regardless if the non-static method uses an instance variable or not.
Non-Static methods
A non-static method does not have the keyword static before the name of the method.
A non-static method belongs to an object of the class and you have to create an instance of the class to access it.
Non-static methods can access any static method and any static variable without creating an instance of the class.
So you'd better think if you need to define studentList as static or no, and if modify your code accordingly.
P.S. above written is taken from here
The difference between static (global, class level) and non-static (a instance of that class, an object) is important.
Creating an object by new Main() allows to work on that object and its fields.
The static void main(String[]) is the single entry point to the application.
Inside the main you have access only to static fields and static methods. So that is cumbersome.
package srivastava.arpit; // In a directory path srivastava/arpit/
import java.util.ArrayList;
public class Main {
private ArrayList studentList = new ArrayList<>();
public static void main(String []args) {
Main main = new Main();
main.execute();
}
private void execute() {
addStudent("Adam", "Goldsmith", 70, 50);
addStudent("John", "Smith", 20, 40);
addStudent("Lewis", "Peterson", 90, 85);
for (Student obj: studentList){
System.out.println("Name: " + obj.studentForename + " "+ obj.studentSurname);
}
}
public void addStudent(String forename, String surname, int coursework, int test) {
Student newStudent = new Student(forename, surname);
newStudent.setForename(forename);
newStudent.setSurname(surname);
newStudent.averageMark(70, 65);
studentList.add(newStudent);
}
}
I have 3 classes, say: ShareType, ShareTypesTrue and Main.
public class ShareType {
public String shareTypeName = "";
public String noOfShare = "";
public String parValue = "";
public void setShareTypeName(String shareTypeName) {
this.shareTypeName = shareTypeName;
}
public void setNoOfShare(String noOfShare) {
this.noOfShare = noOfShare;
}
public void setParValue(String parValue) {
this.parValue = parValue;
}
}
public class ShareTypesTrue {
public List<ShareType> shareType;
public void setShareType(List<ShareType> shareType) {
this.shareType = shareType;
}
}
public class Main {
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
sharetypetrue.add(shareTypeName);
}
Now my problem is i need to set shareTypeName to a value under the class ShareTypesTrue. Meaning i have to use ShareTypesTrue to call on the Sharetype class and set the shareTypeName.
Anyone has an idea?
NOTE: I cant change/add code in the first 2 classes except in main. i just need to find a way to get around this.
Thanks Alot
Please check below code for Main class.
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String args[]){
ShareTypesTrue sharetypetrue = new ShareTypesTrue();
//Create object
ShareType shareType = new ShareType();
shareType.setShareTypeName("Original Name");
//Create list
List<ShareType> shareTypes=new ArrayList<ShareType>();
shareTypes.add(shareType);
//Attach it to share
sharetypetrue.setShareType(shareTypes);
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
//Editing it.
for(ShareType shareTypesMember:sharetypetrue.shareType){
shareTypesMember.shareTypeName = "Updated Name";
}
//Print
for(ShareType shareTypesMember:sharetypetrue.shareType){
System.out.println(shareTypesMember.shareTypeName);
}
}
}
Use Sharetype class to set the shareTypeName
ShareType share = new ShareType();
share.setShareTypeName("name");
share.setNoOfShare("no");
share.setParValue("val");
List<ShareType> shareType = new ArrayList<ShareType>();
shareType.add(share);
use ShareTypesTrue to set Sharetype
ShareTypesTrue sharetrue = new ShareTypesTrue();
sharetrue.setShareType(shareType);//pass ShareType as list
If you want to set the 'name' in ShareType, what prevents you from doing the below:
class ShareTypeTrue_Extended extends ShareTypeTrue{
protected shareTypeName;
public ShareTypeTrue_Extended(String shareTypeName){this.shareTypeName=shareTypeName;}
public void setShareType(List<ShareType> shareType) {
for(ShareType s: shareType)s.setShareTypeName(this.shareTypeName);
super.setShareType(shareType);
}
}
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
This if my first question on stackoverflow. I can usually find answers myself but I'm having trouble with this one. I've got 2 objects, "Book", and "Periodical". These are subclasses to a class "Publication". Now, I'm trying to add 3 instances of "Book" and 3 instances of "Periodical" to an ArrayList. I'm having trouble figuring out how to do this.
With this current code, I get an error "no suitable method found for add(Book,Book,Book,Periodical,Periodical,Periodical).
Here is the current code:
import java.util.ArrayList;
import java.util.Date;
public class DriverProgram {
public static void main(String[] args) {
// Instantiate 3 instances of each object.
Book book1 = new Book(1234, 1, "James", 100, "Hello", "Berkwood Inc.", new java.util.Date(), "History");
Book book2 = new Book(2345, 2, "Ralph", 200, "Goodbye", "Shackles Co.", new java.util.Date(), "English");
Book book3 = new Book(3456, 3, "Julia", 300, "Hello Again", "Trustin Inc.", new java.util.Date(), "History");
Periodical periodical1 = new Periodical("Daily", "Dylan", "History 101", "History Inc.", new java.util.Date(), "History");
Periodical periodical2 = new Periodical("Weekly", "Jannette", "Mathematics 101", "Mathematics Inc.", new java.util.Date(), "Mathematics");
Periodical periodical3 = new Periodical("Monthly", "Patricia", "Science 101", "Science Inc.", new java.util.Date(), "Science");
// Create an array list of the Publication class type, and add the objects to it.
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
// Pass the array list to a method to loop through it and display the toString methods.
displayObjects(publications);
} // End of main
static void displayObjects (ArrayList<Publication> publications) {
// Loop through array list and display the objects using the toString methods.
for (Publication p : publications) {
System.out.print(p.toString());
} // End of for each loop
} // End of displayObjects
} // End of DriverProgram class
I've also tried changing:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
To this:
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
Which rids my program of the compiler error, but then it just prints the "periodical3" object, 6 times. I'm not sure what I'm doing wrong. Any suggestions? Thank you in advance! :)
EDIT:
Here is my Book class:
public class Book extends Publication{
private static int isbn = 0;
private static int libraryOfCongressNbr = 0;
private static String author = "";
private static int nbrOfPages = 0;
// Constructor for Book class with parameters for each attribute.
public Book(int newISBN, int newLibraryOfCongressNbr, String newAuthor, int newNbrOfPages, String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject) {
super(newTitle, newPublisher, newPublicationDate, newSubject);
isbn = newISBN;
libraryOfCongressNbr = newLibraryOfCongressNbr;
author = newAuthor;
nbrOfPages = newNbrOfPages;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
int getISBN() {
return isbn;
}
int getLibraryOfCongressNbr() {
return libraryOfCongressNbr;
}
String getAuthor() {
return author;
}
int getNbrOfPages() {
return nbrOfPages;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setISBN(int newISBN) {
isbn = newISBN;
}
void setLibraryOfCongressNbr(int newLibraryOfCongressNbr) {
libraryOfCongressNbr = newLibraryOfCongressNbr;
}
void setAuthor(String newAuthor) {
author = newAuthor;
}
void setNbrOfPages(int newNbrOfPages) {
nbrOfPages = newNbrOfPages;
}
//toString method for Book class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nISBN: " + isbn + "\n");
result.append("\nPublisher: " + libraryOfCongressNbr + "\n");
result.append("\nAuthor: " + author + "\n");
result.append("\nNumber of Pages: " + nbrOfPages + "\n");
result.append("--------------------------------------------------------- ");
return super.toString() + result.toString();
} // End of toString
} // End of Book class
My Periodical class is identical, but here is my Publication class:
import java.util.Date;
public abstract class Publication {
// Data fields.
private static String title = "";
private static String publisher = "";
private static java.util.Date publicationDate;
private static String subject = "";
// Constructor for Publication class with parameters for each attribute.
public Publication(String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject){
title = newTitle;
publisher = newPublisher;
publicationDate = newPublicationDate;
subject = newSubject;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
String getTitle() {
return title;
}
String getPublisher() {
return publisher;
}
java.util.Date getPublicationDate() {
return publicationDate;
}
String getSubject() {
return subject;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setTitle(String newTitle) {
title = newTitle;
}
void setPublisher(String newPublisher) {
publisher = newPublisher;
}
void setPublicationDate(java.util.Date newPublicationDate) {
publicationDate = newPublicationDate;
}
void setSubject(String newSubject) {
subject = newSubject;
}
//toString method for Publication class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nTitle: " + title + "\n");
result.append("\nPublisher: " + publisher + "\n");
result.append("\nPublication Date: " + publicationDate + "\n");
result.append("\nSubject: " + subject + "\n");
return result.toString();
} // End of toString
} // End of Publication class
Let me know if you need anything else!
EDIT x2: Sorry, I realize my post is getting quite long.
So I've gotten rid of all "static" keywords from my class variables, or "data fields" as I've called them in my code. I then changed my code back to this code:
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
And it works! It executes as it should! I just one question though, since this code doesn't seem to work:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
Is there a shorter way to add all of the objects to the ArrayList with out doing it one by one?
If I understand the problem correctly, you have 6 Publication objects, and you are only seeing the values of the most recently created one.
That would likely be caused because you have static class variables instead of instance variables.
For example
class A {
static int x; // class variable
int y; // instance variable
public A(int val) {
x = val; // All 'A' classes now have x = val;
y = val; // Only 'this' class has y = val;
}
}
If I were to run this
A a1 = new A(4);
A a2 = new A(5);
System.out.println(a1.x);
Then I would see it print 5 and not 4, which describes the scenario you are seeing because you have assigned all variables in the Publication class to those that you use during the last call of new Periodical.
The solution is to not use static variables if you want to have multiple instances of a class with their own values.
Im pretty new to Java. I'm trying to connect these classes together. The Go class, is the main class, that should end up running the program. According to Eclipse, the program doesn't contain any errors, but while running, the outprint is blank.
The Go class:
public class Go {
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
}
}
The Ansat class:
import java.util.ArrayList;
public class Ansat {
public String navn;
public int alder;
public Ansat(String navn, int alder, ArrayList<Ansat> ansat){
this.navn = navn;
this.alder = alder;
}
public int getAlder() {
return alder;
}
public void setAlder(int alder) {
this.alder = alder;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
}
The Data class:
import java.util.ArrayList;
public class Data {
private ArrayList<Ansat> ansat;
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
}
public ArrayList<Ansat> getAnsat() {
return ansat;
}
}
Output the contents of ArrayList to console
public class Go {
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
for(Ansat ansat : getAnsat()){
system.out.println(ansat.getNavn(), ansat.getAlder());
}
}
}
I recommend just two modifications for you to get a proper readable output.
Add the following method to your Ansat class
//modify the returned string however you want it to appear
public String toString() {
return navn + " , " + alder;
}
and then add this line in your main method of Go class (last statement)
System.out.println(klasseObject.getAnsat().get(0).toString());
The toString() class that is added to the Ansat is overriding the toString() method for Ansat meaning that it allows you to print the fields of Ansat class the way you want it and whenever you invoke toString() on object of Ansat then it will pretty print it for you such as below:
Hej , 123
You can update the toString() method to print it however you want.
If you wish to have more than one element in your ArrayList then you have to do the following changes (but, I do want state that you are not doing this the right way):
Data klasseObject = new Data();
klasseObject.infoListe();
Data klasseObject2 = new Data();
klasseObject.infoListe();
Data klasseObject3 = new Data();
klasseObject.infoListe();
for(Ansat s: klasseObject.getAnsat())
System.out.println(s.toString());
And this changes to your Data class
public void infoListe(){
if(ansat != null) {
ansat.add(new Ansat("Hej", 123, ansat));
} else {
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
}
}
If I were to review your code and suggest improvements, then I would do the following changes in your classes (copy/paste the following code Go.java file and run it):
import java.util.ArrayList;
public class Go {
public static void main(String[] args) {
// running below creates an ArrayList<Ansat> that is inside KlasseObject
Data klasseObject = new Data();
// creates one Ansat(Hey,123) and add it to list
klasseObject.setData("Hey", 123);
// creates one Ansat(Raf,555) and add it to list
klasseObject.setData("Raf", 555);
// creates one Ansat(X-men,999) and add it to list
klasseObject.setData("X-men", 999);
//as many classes as you want, it would add them all to the list
//of klasseObject
// now that we set three Ansats, we will retrieve the list and print
// them all
for (Ansat s : klasseObject.getAnsatList())
System.out.println(s.toString());
}
}
class Ansat {
public String navn;
public int alder;
//remove the array list from constructor, not needed
public Ansat(String navn, int alder) {
this.navn = navn;
this.alder = alder;
}
public int getAlder() {
return alder;
}
public void setAlder(int alder) {
this.alder = alder;
}
public String getNavn() {
return navn;
}
public void setNavn(String navn) {
this.navn = navn;
}
//overrided toString method to pretty-print Ansat object
public String toString() {
return navn + " , " + alder;
}
}
class Data {
private ArrayList<Ansat> ansat;
// added the constructor for Data to initialize Data with empty list
public Data() {
ansat = new ArrayList<Ansat>();
}
//replaced infoListe to setData and added args to it so you can
//pass them from main method
public void setData(String name, int age) {
// every time setData is called a new Ansat is added to list
Ansat a = new Ansat(name, age);
ansat.add(a);
}
public ArrayList<Ansat> getAnsatList() {
return ansat;
}
}
Actually the process what you have followed is perfectly correct,But your getting blank because your not printing the arraylist, hence your getting blank output. Just add the below line and you will see the correct output.
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
System.out.println(ansat);
}
or in the main function just use it like this...
public static void main(String[] args) {
Data klasseObject = new Data();
klasseObject.infoListe();
System.out.println(klasseObject.getAnsat());
}
Even iterating over array list will fetch you the output -
for (Ansat ansatLoop : klasseObject.getAnsat()) {
System.out.println(ansatLoop.getAlder() + ":"
+ ansatLoop.getNavn());
}
I hope this would solve your query.
Your code is working Perfectly! It has no
System.out.println();
anywhere in the methods that run.
If you modify the method infoListe() to add a println it will print something out
public void infoListe(){
ansat = new ArrayList<Ansat>();
ansat.add(new Ansat("Hej", 123, ansat));
System.out.println("Element Added to ArrayList");
}