Want to add a table of objects into array list - java

As I said in theme, but when I am trying to set a new object, the old ones looks same as the last one:
public class Test {
private static List<Booking> list = new ArrayList<Booking>();
private static List<Booking> lista = new ArrayList<Booking>();
public static void main(String[] args)
{
Booking[] book=new Booking[3];
book[0]=new Booking();
book[1]=new Booking();
book[2]=new Booking();
list.add(0,book[0]);
list.add(1,book[1]);
list.add(2,book[2]);
list.get(0).setYear("1900");
list.get(0).setMonth("january");
list.get(1).setMonth("september");
list.get(1).setYear("1600");
list.get(2).setYear("2000");
list.get(2).setMonth("may");
System.out.println(list.get(0).getBook());
System.out.println(list.get(1).getBook());
System.out.println(list.get(2).getBook());
}
}
And the booking class:
public class Booking
{
public static String getMark()
{
return m;
}
public static String getWym()
{
return w;
}
public static String getWyw()
{
return wyw;
}
public static String getImie()
{
return imie;
}
public static String getNaz()
{
return nazwis;
}
public static String getNr()
{
return nr;
}
public void setMark(String m)
{
this.m=m;
}
public void setWym(String w)
{
this.w=w;
}
public void setWyw(String wyw)
{
this.wyw=wyw;
}
public void setImie(String imie)
{
this.imie=imie;
}
public void setNaz(String nazwis)
{
this.nazwis=nazwis;
}
public void setNr(String nr)
{
this.nr=nr;
}
public void setYear(String year)
{
this.year=year;
}
public void setMonth(String month)
{
this.month=month;
}
public void setDay(String day)
{
this.day=day;
}
public void setHour(String hour)
{
this.hour=hour;
}
public static String getYear()
{
return year;
}
public static String getMonth()
{
return month;
}
public static String getDay()
{
return day;
}
public static String getHour()
{
return hour;
}
public String getBook()
{
String Book=getYear()+getMonth()+getDay()+getHour()+getMark()+getWym()+getWyw()+getImie()+getNaz()+getNr();
return Book;
}
private static String year;
private static String month;
private static String day;
private static String hour;
private static String m;
private static String w;
private static String wyw;
private static String imie;
private static String nazwis;
private static String nr;
}
Here is what I got after compilation:
2000maynullnullnullnullnullnullnullnull
2000maynullnullnullnullnullnullnullnull
2000maynullnullnullnullnullnullnullnull
Instead of:
1900januarynullnullnullnullnullnullnullnull
1600septembernullnullnullnullnullnullnullnull
2000maynullnullnullnullnullnullnullnull

remove the static from your all your fields in Booking

You are using static variables inside your Booking class and because of this all instances have common fields year, month, etc...
Making field static is like attaching it to whole class context not instance.
The effect is that the last modification (setting may 2000) is modifying all instances in result
You should make these fields non static and then instances will have their own values
class Booking {
private String year;
private String month;
private String day;
//another fields...
public String getYear() {
return this.year;
}
//another methods...
}
Also take a look at reference to understand usage of static keyword. You definitely abuse it.

Related

Error while mering 2 groups (Im a beginner)

So I have a MusicBand Class and I want to create a method that merges members of 2 different groups into one and clears the empty one.
public class MusicBand {
private int year;
private String name;
private List<String> members;
public MusicBand(String name, int year, List<String> members) {
this.name = name;
this.year = year;
this.members = members;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<String> getMembers() {
return members;
}
public void setMembers(List<String> members) {
this.members = members;
}
public static void transferMembers(MusicBand a, MusicBand b) {
for (String members : a.getMembers()) {
b.getMembers().add(members);
a.getMembers().clear();
}
}
public void printMembers(){
System.out.println(this.members);
}
}
public class Test4 {
public static void main(String[] args) {
List<String> members1 = new ArrayList<>();
members1.add("a");
members1.add("b");
members1.add("c");
List<String>members2 = new ArrayList<>();
members2.add("a2");
members2.add("b2");
members2.add("c2");
MusicBand group1 = new MusicBand("aaa",1990,members1);
MusicBand group2 = new MusicBand("bbb",2010,members2);
group1.printMembers();
group2.printMembers();
MusicBand.transferMembers(group1,group2);
}
}
So it prints out 2 groups and then instead of merging this happens "Exception in thread "main" java.util.ConcurrentModificationException"
What can I do to fix this?
Thanks in advance.
Move your a.getMembers().clear(); method outside your for loop.
In fact your transferMembers() method could look like the following:
public static void transferMembers(MusicBand a, MusicBand b) {
b.getMembers().add(members);
a.getMembers().clear();
}
There is no need for a for loop at all.
It is also bad practice to use a static method for this. So, your MusicBand class should just have a method to add members to it. So, instead of your static transferMembers(...) method you should have these two:
public void addMembers(MusicBand otherBand) {
getMembers().addAll(otherBand.getMembers());
}
public void clear() {
getMembers().clear();
}
You can then decide whether to call clear() from the calling class or inside the addMembers() method.

Error with writing to a file in Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am getting the following errors.
Exception in thread "main" java.lang.NullPointerException at ReadFile.createDogs(ReadFile.java:41) at ReadFile.main(ReadFile.java:55)
The file is opening to the desktop. I feel I am missing something very
simple. I have included the class file also. The error is specific to
dogOutput.println(dogInfo);
Thank you.
import java.io.*;
import java.io.PrintWriter;
public class ReadFile
{
private static Canine[] getCanine()
{
Canine[] canines= new Canine[5];
canines[0]=new Canine("Thoedore", "Male", "Medium", 7, 50);
canines[1]=new Canine("Magellan", "Male", "Medium", 5, 50);
canines[2]=new Canine("Duffy", "Male", "Small", 10, 10);
canines[3]=new Canine("Sammie", "Female", "Medium", 7, 65);
canines[4]=new Canine("Snowball", "Male", "Small", 13, 17);
return canines;
}
private static PrintWriter createFile(String fileName)
{
try{
File listOfDogs = new File(fileName);
PrintWriter infoToWrite= new PrintWriter
( new BufferedWriter
(new FileWriter(listOfDogs)));
}
catch (IOException e)
{
System.out.println(" An I/O Error Occurred.");
System.exit(0);
}
return null;
}
private static void createDogs(Canine dog, PrintWriter dogOutput)
{
String dogInfo= dog.name + " " + dog.gender+ " " + dog.size +" ";
dogInfo += Integer.toString(dog.age)+ " "+
Double.toString(dog.weight);
dogOutput.println(dogInfo);
}
public static void main (String[] args)
{
Canine[] canines= getCanine();
System.out.println("Here1");
PrintWriter dogOutput =
createFile("/Users/Teacher/Desktop/Dogs.text");
for(Canine dogs: canines)
{
createDogs(dogs, dogOutput);
System.out.println("Here5");
}
dogOutput.close();
}
private static class Canine extends Pet
{
public static final String type="Dog";
public Canine()
{
super.type=this.type;
}
public Canine(String name, String gender, String size, int age, double
weight)
{
super.type=this.type;
super.name=name;
super.gender=gender;
super.size=size;
super.age=age;
super.weight=weight;
}
public static void setType(String word)
{
}
}
private static class Pet
{
public static String type;
public static String color;
public static String gender;
public static String temperment;
public static String food;
public static int age;
public static double weight;
public static String name;
public static String size;
public Pet()
{
}
public Pet(String type,String color,String gender,String temperment,
String food,int age,double weight,String name,String size)
{
type=type;
color=color;
gender=gender;
temperment=temperment;
food=food;
age=age;
weight=weight;
name=name;
size=size;
}
public Pet(String name, String gender, String size, int age, double
weight)
{
name=name;
gender=gender;
size=size;
age=age;
weight=weight;
}
public static String getType()
{
return type;
}
public static String getName()
{
return name;
}
public static String getSize()
{
return size;
}
public static String getColor()
{
return color;
}
public static String getTemperment()
{
return temperment;
}
public static String getFood()
{
return food;
}
public static String getGender()
{
return gender;
}
public static int getAge()
{
return age;
}
public static void setType(String word)
{
type=word;
}
public static void getName(String word)
{
name=word;
}
public static void setSize(String word)
{
size=word;
}
public static void setColor(String word)
{
color=word;
}
public static void getTemperment(String word)
{
temperment=word;
}
public static void setFood(String word)
{
food=word;
}
public static void setGender(String word)
{
gender=word;
}
public static void setAge(int ageSet)
{
age=ageSet;
}
public static void setWeight(double weightSet)
{
weight=weightSet;
}
public static void setName(String NameSet)
{
name=NameSet;
}
public String toString()
{
return ("Type "+type+"\n" +" Name "+name+"\n"+" Age "+age+"\n"+
"Size "+ size+"\n"+" Gender "+gender+"\n"+" Weight "+weight);
}
}
}
Try renaming the dogOutput variable. In java, you can't pass variables between static methods with the same name.
The simple answer: In createFile() you always return null instead of the instance of PrintWriter you just created as infoToWrite.
The complete answer: You need to strengthen your knowledge of OOP. The unnecessary use of static members, for instance, can have undesired effects.

Iterating and searching in LinkedList

I am printing LinkedList like this:
public class cinema{
public static LinkedList <cinema> cinList = new LinkedList<cinema>();
private int cinemaNum,numSeats;
private String row;
public cinema(int getCinemaNumber,String getRowName,int getNumSeats){
this.cinemaNum = getCinemaNumber;
this.row = getRowName;
this.numSeats = getNumSeats;
//todo
}
public static void addHalls(cinemaValues cin){
cinema Cinema = new cinema(cin.getCinemaNumber(), cin.getRowName(),cin.getNumSeats());
cinList.add(Cinema);
}
public static void print(){
System.out.println(cinList);
}
#Override
public String toString() {
return "cinnum:"+cinemaNum+" row:"+row+" seats:"+numSeats;
}
}
public class session{
public static LinkedList <session> sessList = new LinkedList<session>();
private int CinemaSessionNum;
private String time,movie;
public session(int getCinemaSessionNum, String getTime,String getMovie){
this.CinemaSessionNum = getCinemaSessionNum;
this.time = getTime;
this.movie = getMovie;
}
public static void addSession(CinemaSessions sess){
session ses = new session(sess.getCinemaSessionNum(),sess.getTime(),sess.getMovie());
sessList.add(ses);
}
public static void print(){
System.out.println(sessList);
}
#Override
public String toString() {
return "cinnum:"+CinemaSessionNum+" time:"+time+" movie:"+movie;
}
}
the output:
I want a way to be able search all three parts of an elements using one of the keys
basically,
when the condition is Cinnum:2 I want it to return
Cinnum:1 time:9:00 movie:toy
Cinnum:1 time:14:30 movie:Ratatouille
Any help would be appreciated.
Thanks

can i print a setter value (sysout) or do i have to use only getters in order to get an output ? (java)

I have just recently learned about setter , getters and this.(somthing).
I having quite a hard time undersatnding when to use getters and when to use setters .
Another thing , can i use setter method to print out ?
For Example :
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
newAge = workerAge;
}
public void setWorkerName(String newName) {
newName = workerName;
}
public int setIde(int ide) {
ide = workerIde;
return ide;
}
}
public class App {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.setIde());
}
}
the system out print shows an error and i didnt understand why , is it because only getters can be used in the sysout command ?
No offense intended, but your setters are all wrong. You should assign your properties to the values passed in the setter, not setting the value again. So your code should look like this:
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName = newName;
}
public int setIde(int ide) {
workerIde = ide;
}
}
If you need getters, it should look like this:
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName = newName;
}
public int setIde(int ide) {
workerIde = ide;
}
public int getIde() {
return workerIde;
}
}
Then you can print, e.g. System.out.println(worker1.getIde());
You should be using a getter method to get the values.
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
workerAge = newAge;
}
public void setWorkerName(String newName) {
workerName=newName;
}
public int getIde() {
return workerIde;
}
public void setIde(int ide) {
workerIde = ide;
}
}
public class App {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.getIde());
}
}
class workerId {
private int workerAge;
private String workerName;
private int workerIde;
public void setWorkerAge(int newAge) {
this.workerAge = newAge;
}
public void setWorkerName(String newName) {
this.workerName = newName;
}
public int setIde(int ide) {
this.workerIde = ide;
return this.workerIde;
}
}
public class Car {
public static void main(String[] args) {
workerId worker1 = new workerId();
worker1.setWorkerAge(41);
worker1.setWorkerName("dan ");
worker1.setIde(318574524);
System.out.println(worker1.setIde(56));
}
}

Java FX populate tableview with specific model

Hello I have got a question about TableView in JavaFX and populating the table with data from an object in the model via a getter method of this object, which is part of the model .
First of all, here is my model:
package model;
import java.util.List;
public class Carmodel {
private int carmodelID;
private Cartype cartype;
private Manufacturer manufacturer;
private DrivingLicense drivingLicense;
private String label;
private int seats;
private int kw;
private String fuelType;
private double priceDay;
private double priceKM;
private int axes;
private int loadVolume;
private int loadCapacity;
private List<Equipment> equipmentList;
public Carmodel() {
}
public int getCarmodelID() {
return carmodelID;
}
public void setCarmodelID(int carmodelID) {
this.carmodelID = carmodelID;
}
public Cartype getCartype() {
return cartype;
}
public void setCartype(Cartype cartype) {
this.cartype = cartype;
}
public Manufacturer getManufacturer() {
return manufacturer;
}
public void setManufacturer(Manufacturer manufacturer) {
this.manufacturer = manufacturer;
}
public DrivingLicense getDrivingLicense() {
return drivingLicense;
}
public void setDrivingLicense(DrivingLicense drivingLicense) {
this.drivingLicense = drivingLicense;
}
public String getLabel() {
return label;
}
public void setLabel(String label) {
this.label = label;
}
public int getSeats() {
return seats;
}
public void setSeats(int seats) {
this.seats = seats;
}
public int getKw() {
return kw;
}
public void setKw(int kw) {
this.kw = kw;
}
public String getFuelType() {
return fuelType;
}
public void setFuelType(String fuelType) {
this.fuelType = fuelType;
}
public double getPriceDay() {
return priceDay;
}
public void setPriceDay(double priceDay) {
this.priceDay = priceDay;
}
public double getPriceKM() {
return priceKM;
}
public void setPriceKM(double priceKM) {
this.priceKM = priceKM;
}
public int getAxes() {
return axes;
}
public void setAxes(int axes) {
this.axes = axes;
}
public int getLoadVolume() {
return loadVolume;
}
public void setLoadVolume(int loadVolume) {
this.loadVolume = loadVolume;
}
public int getLoadCapacity() {
return loadCapacity;
}
public void setLoadCapacity(int loadCapacity) {
this.loadCapacity = loadCapacity;
}
public List<Equipment> getEquipmentList() {
return equipmentList;
}
public void setEquipmentList(List<Equipment> equipmentList) {
this.equipmentList = equipmentList;
}
As you can see there is a specific member (private Manufacturer manufacturer) It is an object from the type "Manufacturer". And the Manufacturer class looks like this:
public class Manufacturer {
private int manufacturerID;
private String name;
public Manufacturer() {
}
public int getManufacturerID() {
return manufacturerID;
}
public void setManufacturerID(int manufacturerID) {
this.manufacturerID = manufacturerID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is my controller for the JavaFX View:
public class CarmodelController implements Initializable {
CarmodelRepository carmodelRepository;
#FXML public TableView CarmodelTable;
#FXML public TableColumn<Carmodel,Integer> tableColumnID ;
#FXML public TableColumn<Carmodel,String> tableColumnLabel ;
#FXML public TableColumn<Carmodel, String> tableColumnManufacturer ;
#FXML public TableColumn<Carmodel,String> tableColumnCartype ;
public void initialize(URL location, ResourceBundle resources) {
carmodelRepository= new CarmodelRepository();
List<Carmodel> carmodelList= carmodelRepository.readAll();
ObservableList<Carmodel> carmodelObservableList = FXCollections.observableArrayList(carmodelList);
tableColumnID.setCellValueFactory(new PropertyValueFactory<Carmodel, Integer>("carmodelID"));
tableColumnLabel.setCellValueFactory(new PropertyValueFactory<Carmodel, String>("label"));
tableColumnManufacturer.setCellValueFactory(new PropertyValueFactory<Carmodel, String>("manufacturer")
And here is the problem:
Can I do here something like PropertyValueFactory("manufacturer.getName()"); This way it didn't work. It just populate the column of the table with memory adress
So my question is:
How can I get the name of the manufacturer, normally, in other code, you can do this by calling the method: "manufacturer.getName();" and it will give you the String with the name of the manufacturer, but how can I do this while I will populate the table with these specific carmodels?
And the end of the controller code ( filling the Table with values).
CarmodelTable.setItems(carmodelObservableList);
}
Thank you in advance!
You can do
tableColumnManufacturer.setCellValueFactory(cellData ->
new ReadOnlyStringWrapper(cellData.getValue().getManufacturer().getName());
The setCellValueFactory method expects a Callback<CellDataFeatures<Carmodel, String>, ObservableValue<String>> object. Hence cellData in this code is a CellDataFeatures<Carmodel, String> object, and cellData.getValue() gives the CarModel object for the row. Then cellData.getValue().getManufacturer().getName() gives the value you want; you just have to wrap it in a ReadOnlyObservableWrapper to get an ObservableValue<String> containing that value.

Categories