Sorry as I know this is obvious but I cant figure it out!
I have a parent class named 'Set', representing a set of a tennis match.
public class Set {
private String set1;
private String set2;
private String set3;
//private Object[] match;
public Set() {
setSet1(set1);
setSet2(set2);
setSet3(set3);
}
public void setSet1(String set1) {
this.set1 = set1;
}
public String getSet1() {
return set1;
}
public void setSet2(String set2) {
this.set2 = set2;
}
public String getSet2() {
return set2;
}
public void setSet3(String set3) {
this.set3 = set3;
}
public String getSet3() {
return set3;
}
public String toString(){
return String.format("set1: %s, set2: %s, set3: %s", set1, set2, set3);
}
}
And a sub class of 'Set' named 'SingleSet', where i try to add the sets into an array named 'game':
public class SingleSet extends Set{
private Object homePlayer;
private Object awayPlayer;
private String[] game;
public SingleSet(Object homePlayer, Object awayPlayer){
super();
game = new String[3];
game[0] = super.getSet1();
game[1] = super.getSet2();
game[2] = super.getSet3();
setHomePlayer(homePlayer);
setAwayPlayer(awayPlayer);
}
public void setHomePlayer(Object homePlayer) {
this.homePlayer = homePlayer;
}
public Object getHomePlayer() {
return homePlayer;
}
public void setAwayPlayer(Object awayPlayer) {
this.awayPlayer = awayPlayer;
}
public Object getAwayPlayer() {
return awayPlayer;
}
public void setGame(String[] game) {
this.game = game;
}
public String[] getGame() {
return game;
}
public String toString(){
return String.format("Player: %s Vs. Player: %s, Single set game: %s, %s, %s", homePlayer, awayPlayer, game[0], game[1], game[2]);
}
}
And this is where I am trying to add the Sets from my parents class into my sub class (this is for FXML, so the code is in my controller):
public void submit() {
SingleSet game1 = new SingleSet(homePlayer1Dropdown.getValue(), awayPlayer1Dropdown.getValue());
game1.setSet1(set1Box1.getText());
game1.setSet2(set1Box2.getText());
game1.setSet3(set1Box3.getText());
System.out.println(game1);
When I print the result, all my values are null. I tried printing them individually and that worked fine, so I know the 'set1Box.getText()' is working fine.
Again sorry for any obvious rookie error!
I've updated my code and same issue. Thank you for the composition answer, I will need it for my project, but this is a IS-A relationship
Make sure that the toString() methods of the following attributes exist and return a correct string.
It seems as if there is no way to get a String from homePlayer, awayPlayer and all indices of game[x].
public String toString(){
return String.format("Player: %s Vs. Player: %s, Single set game: %s, %s, %s", homePlayer, awayPlayer, game[0], game[1], game[2]);
}
Related
I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
gp1.agregar(v1);
//gp1.mostrar(v1);
gp1.agregar(v2);
System.out.println(gp1.check());
GrandPrix gp2 = new GrandPrix();
gp2.agregar(vt1);
gp2.agregar(vt2);
gp2.agregar(m2);
System.out.println(gp2.check());
GrandPrix gp3 = new GrandPrix();
gp3.agregar(vt1);
gp3.agregar(vt2);
gp3.agregar(m1);
System.out.println(gp3.check());
GrandPrix gp4 = new GrandPrix();
gp4.agregar(m1);
gp4.agregar(m2);
System.out.println(gp4.check());
This is the class that is using
import java.util.ArrayList;
public class GrandPrix extends Rally{
ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();
public void agregar(Vehiculo v) {
ve.add(v);
}
public void agregar(Carro c) {
ve.add(c);
}
public void agregar(Moto m) {
ve.add(m);
}
#Override
boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
return false;
}
}
This is the class where everything goes on
public class Vehiculo {
private String Nombre;
private double velocidad_max;
private int peso;
private int comb;
public Vehiculo() {
setNombre("Anónimo");
setVel(130);
setPeso(1000);
setComb(0);
}
public Vehiculo(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
}
double rendimiento() {
return velocidad_max/peso;
}
public boolean mejor(Vehiculo otroVehiculo) {
return rendimiento()>otroVehiculo.rendimiento();
}
public String toString() {
return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
}
/**************************************
---------SET And GET Nombre------------
***************************************/
public String getNombre() {
return Nombre;
}
public void setNombre(String nuevoNombre) {
this.Nombre=nuevoNombre;
}
/**************************************
---------SET And GET velocidad_max------------
***************************************/
public double getVel() {
return velocidad_max;
}
public void setVel(double nuevaVel) {
this.velocidad_max=nuevaVel;
}
/**************************************
---------SET And GET peso------------
***************************************/
public double getPeso() {
return peso;
}
public void setPeso(int nuevoPeso) {
this.peso=nuevoPeso;
}
/**************************************
---------SET And GET comb------------
***************************************/
public int getComb() {
return comb;
}
public void setComb(int comb) {
this.comb = comb;
}
boolean esDe2Ruedas() {
return false;
}
}
This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{
private boolean sidecar;
public Moto(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(false);
}
public Moto(String string, double d, int i, int j, boolean b) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(b);
esDe2Ruedas(false);
}
public String toString() {
String str = null;
if(isSidecar())
str =super.toString()+", Moto, con sidecar";
else
str =super.toString()+", Moto";
return str;
}
public boolean isSidecar() {
return sidecar;
}
public void setSidecar(boolean sidecar) {
this.sidecar = sidecar;
}
I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.
i am trying to write a class which has an array of a subclass in the same project, and when i am trying to write a method that will add a new object to the array on condition that this object is not already in the array, and also if the specific cell is free, so the object will enter to the array.
but the problem is that i need to insert a variable to this method which is the copy constructor's object.
the problem is that in the subclass i don't know how to write the copy constructor.
so i will give a short example of 2 classes and you will show me how to write a copy constructor with them :
public class Food
{
private String _foodName;
public Food(String foodName)
{
_foodName=foodName;
}
public String getFoodName()
{
return _foodName;
}
public void showName()
{
System.out.println("The food's name is: " +_getFoodName());
}
}
public class Apple extends Food
{
private int _numOfApples;
public Apple(String name, int numOfApples)
{
super(name);
_numOfApples=numOfApples;
}
public Apple(Apple other)
{
????
}
}
how does the copy constructor should looks like ?
thank you for your help :)
By invoking the other constructor. Like,
public Apple(Apple other) {
this(other.getFoodName(), other._numOfApples);
}
I cannot help you properly because i cannot understand entirely what you are trying to do but at least i can help you correct some mistakes in your code:
public class Food
{
private String food;
public Food(String foodName)
{
food = foodName;
}
public String getFoodName()
{
return food;
}
public void showName()
{
System.out.println("The food's name is: " + getFoodName());
}
}
public class Apple extends Food
{
private int numOfApples;
public Apple(String name, int numberOfApples)
{
super(food);
numOfApples=numberOfApples;
}
public Apple(Apple copy)
{
this.name = copy.name;
this.numOfApples = copy.numOfApples;
}
}
Hope this helps.
I have read quite a few pages of stackoverflow but I wasn't able to get my ArrayList to get copied unto another class. Here's the scenario, I'm building a quick book saver app, similar to what you would have in a library but simpler (for school).
I have my main library class (with the main) that has the swing set up for the main menu/options.
I have the book class with the constructor for new books as follows:
public class Livre {
private String titre;
private String soustitre;
private String auteur;
private String editeur;
private String collection;
private String isbn;
private long cup;
private double prixDeVenteSuggere;
private double prixVente;
private int nbPages;
private boolean disponible;
public Livre(String titre, String soustitre, String auteur, String editeur, String collection, String isbn, long cup, double prixDeVenteSuggere, double prixVente, int nbPages, boolean disponible){
this.titre = titre;
this.soustitre = soustitre;
this.auteur = auteur;
this.editeur = editeur;
this.collection = collection;
this.isbn = isbn;
this.cup = cup;
this.prixDeVenteSuggere = prixDeVenteSuggere;
this.prixVente = prixVente;
this.nbPages = nbPages;
disponible = true;
}
public Livre() {
}
public String getTitre() {
return titre;
}
public void setTitre(String titre) {
this.titre = titre;
}
public String getSoustitre() {
return soustitre;
}
public void setSoustitre(String soustitre) {
this.soustitre = soustitre;
}
public String getAuteur() {
return auteur;
}
public void setAuteur(String auteur) {
this.auteur = auteur;
}
public String getEditeur() {
return editeur;
}
public void setEditeur(String editeur) {
this.editeur = editeur;
}
public String getCollection() {
return collection;
}
public void setCollection(String collection) {
this.collection = collection;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public long getCup() {
return cup;
}
public void setCup(long cup) {
this.cup = cup;
}
public double getPrixDeVenteSuggere() {
return prixDeVenteSuggere;
}
public void setPrixDeVenteSuggere(double prixDeVenteSuggere) {
this.prixDeVenteSuggere = prixDeVenteSuggere;
}
public double getPrixVente() {
return prixVente;
}
public void setPrixVente(double prixVente) {
this.prixVente = prixVente;
}
public int getNbPages() {
return nbPages;
}
public void setNbPages(int nbPages) {
this.nbPages = nbPages;
}
public boolean isDisponible() {
return disponible;
}
public void setDisponible(boolean disponible) {
this.disponible = disponible;
}
}
Option #1 on the Library class (built with WindowBuilder) has the "New" button which opens a second JFrame to input all the info in regards to the book.
in this JFrame class, I've added an actionListener on the confirm button to confirm the input on the JTextFields to be added as an object as follows:
public void confirmerLivre(){
l = new Livre(txtTitre.getText(), txtSousTitre.getText(), txtAuteur.getText(),
txtEditeur.getText(), txtCollection.getText(), txtISBN.getText(),
Long.parseLong(txtCodebar.getText()), Double.parseDouble(txtPrixMSRP.getText()),
Double.parseDouble(txtPrix.getText()), Integer.parseInt(txtPages.getText()), true);
confirmerLivre.add(l); /// confirmerLivre is defined as an ArrayList
}
What I can't wrap my head around is being able to take the ArrayList confirmerLivre from the 2nd JFrame class and push it unto my main JFrame class to be manipulated further with other options.
Any help will be greatly appreciated.
Thank you
Probably the quickest fix is to create/expose these methods in your main JFrame class:
getBookList()
setBookList()
When you create your popup JFrame, you need to pass an instance of your main JFrame class to it in its constructor:
public PopupFrame extends JFrame {
private MainFrame main;
public PopupFrame(MainFrame main) {
this.main = main;
}
}
Now that you have access to your main JFrame class from your popup, you can just go main.getBookList() to get the list (I'd recommend reading this question also)
If you create your ArrayList as a public variable in the second JFrame class (outside any of the methods) then it can be used in the first class such as:
SecondJFramesName.confirmerLivre()
In this code SecondJFramesName is the name of your second JFrame class. Now that your ArrayList is a public variable it can be accessed outside the class.
Note: your second JFrame's name is the one you use to create it in a way such as this:
JFrame SecondJFramesName = new JFrame("My title");
If you need any more specific details please comment!
Hopefully this helps!
Maybe observer pattern could help you:
public interface ConfirmerLivreMonitor{
void onConfirmerLivreChange(List<...> confirmerLivre);
}
then
//...
private ConfirmerLivreMonitor confirmerLivreMonitor;
public void setConfirmerLivreMonitor(ConfirmerLivreMonitor confirmerLivreMonitor ){
this.confirmerLivreMonitor = confirmerLivreMonitor
}
//....
public void confirmerLivre(){
l = new Livre(txtTitre.getText(), txtSousTitre.getText(), txtAuteur.getText(),
txtEditeur.getText(), txtCollection.getText(), txtISBN.getText(),
Long.parseLong(txtCodebar.getText()), Double.parseDouble(txtPrixMSRP.getText()),
Double.parseDouble(txtPrix.getText()), Integer.parseInt(txtPages.getText()), true);
confirmerLivre.add(l); /// confirmerLivre is defined as an ArrayList
if(confirmerLivreMonitor != null){ //notify confirmerLivre change
confirmerLivreMonitor.onConfirmerLivreChange(confirmerLivre);
}
}
make the Main JFrame implemnents ConfirmerLivreMonitor,so you can:
sencondJFrame.setConfirmerLivreMonitor(this);
or just pass a anonymous class:
sencondJFrame.setConfirmerLivreMonitor(new ConfirmerLivreMonitor(){
public void onConfirmerLivreChange(List<...> confirmerLivre){
//display in Main JFrame,maybe
}
});
once the confirmerLivre change, the main frame can display(or something else)
the first time,very cool
I am trying to practice with Polymorphism and using classes. I wrote a superclass called Card. I then wrote 3 subclasses called: IDCard, CallingCard, and DriverLicense. I then wrote another class called Billfold which is supposed to contain slots for two of the cards.
I am supposed to write a BillfoldTester program which adds two objects of different subclasses to a Billfold object.
In BillfoldTester, a DriverLicense object and a CallingCard object are instantiated and added to a Billfold, which refers to these objects with Card references.
I don't really understand how to do this. I created two Card objects but I am trying to add it to my Billfold and it wont work. I tried Billfold a = new Card (x); but it's not right... Any help is much appreciated.
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
//Having trouble trying to put the objects into my Billfold and print it.
}
}
public class Billfold extends Card
{
private String card1;
private String card2;
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
}
public class Card
{
private String name;
public Card()
//This is my superclass
{
name = "";
}
public Card(String n)
{
name = n;
}
public String getName()
{
return name;
}
public boolean isExpired()
{
return false;
}
public String format()
{
return "Card holder: " + name;
}
}
public class IDCard extends Card
{
//This is one of my subclasses
private int IDNumber;
public IDCard (String n, int id)
{
super(n);
this.IDNumber=id;
}
public String format()
{
return super.format() + IDNumber;
}
}
The polymorphism example. Not sure if the functionally is exactly what you need, but you can see the whole idea (I hope). See the showAllFormat() method of Billfold class.
The whole point is inside different format() methods of the DriverLicense and IDCard. Depending on the 'real' (or initially assigned) object the different method will be called even if you just only refer to 'Card' class.
NOTE:
You didn't provide your DriverLicense implementation, and my is just from head. I have a bit different constructor to show this sub-classes may be totally different.
import java.util.ArrayList;
import java.util.List;
class Billfold {
List<Card> list = new ArrayList<Card>(10);
void addCard(Card card) // Q: Not sure if this should be String
// A: You would like to add a Card
{
list.add(card);
}
void showAllFormat() {
// go polymorphism !...
// when you call this general 'format()' you see the subclasses
// 'format()' is executed, not from 'Card' class
for(Card x: list) {
System.out.println(x.format());
}
}
}
class Card {
private String name; /* owner */
public Card() //This is my superclass
{
name = "";
}
public Card(String n) {
name = n;
}
public String getName() {
return name;
}
public boolean isExpired() {
return false;
}
public String format() {
return "Card holder: " + name;
}
}
class IDCard extends Card {
//This is one of my subclasses
private int IDNumber;
public IDCard(String n, int id) {
super(n);
this.IDNumber = id;
}
public String format() {
return "(ID)" + super.format() + " " + IDNumber;
}
}
class DriverLicense extends Card {
private String type;
public DriverLicense(String n, String type) {
super(n);
this.type = type;
}
public String format() {
return "(DL)" + super.format() + " TYPE: " + type;
}
}
public class BillfoldTester {
public static void main(String[] args) {
Card x = new IDCard("Julie", 1995);
Card j = new DriverLicense("Jess", "AB");
Billfold bf = new Billfold();
bf.addCard(x);
bf.addCard(j);
bf.showAllFormat();
}
}
This is wrong. A Billfold is not a Card; it HAS Cards.
public class Billfold
{
List<Card> cards = new ArrayList<Card>();
void addCard(Card card) {
if (card != null) {
this.cards.add(card);
}
}
}
Prefer composition over inheritance.
You should have Billfold class have two Card objects, not two Strings:
public class Billfold
{
Card card1;
Card card2;
void addCard(Card card) {
if (card != null) {
if (card1 != null) {
this.card1 = card;
} else {
this.card2 = card;
}
}
}
Ok, you're largely on the right track, just a couple of things:
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
You're right, this should be:
void addCard(Card card)
{
card1=card;
}
then to add them:
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
Billfold bf = new Billfold();
Billfold.addCard(x);
Billfold.addCard(j);
}
}
Then add a method to Billfold to print the cards in it.
Edit: Oh yeah, and duffymo is totally right, you don't need to extends Card on Billfold
consider the below code:
public class Bid {
private double pe;
private List<ResChar> resourceList;
protected Map<Integer,Integer>scheduleOfSeller ;
public Map<Integer, Integer> getScheduleOfSeller() {
return scheduleOfSeller;
}
public void setScheduleOfSeller(Map<Integer, Integer> scheduleOfSeller) {
this.scheduleOfSeller = scheduleOfSeller;
}
private int bidId;
public int getBidId() {
return bidId;
}
public void setBidId(int bidId) {
this.bidId = bidId;
}
public double getPe() {
return pe;
}
public void setPe(double pe) {
this.pe = pe;
}
public List<ResChar> getResourceList() {
return resourceList;
}
public void setResourceList(List<ResChar> resourceList) {
this.resourceList = resourceList;
}
public Bid(int bidId,double pe, List<ResChar> resourceList){
setBidId(bidId);
setPe(pe);
setResourceList(resourceList);
this.scheduleOfSeller = new HashMap<Integer,Integer>();
}
}
I want to make a copy constructor of the bid like this :
public class BidCopy{
public Bid bid;
public BidCopy(Bid bidBuyer){
List<ResChar> resList = new LinkedList<ResChar>();
for (ResChar elt : bidBuyer.getResourceList()){
ResCharCopy eltCopy = new ResCharCopy(elt);
resList.add(eltCopy.elt);
}
this.bid = bidBuyer;
this.bid.setResourceList(resList);
}
}
The only solution that I know to make such copy is to proceed like follows :
public class BidCopy{
public Bid copy;
public BidCopy(Bid bid){
List<ResChar> resList = new LinkedList<ResChar>();
for (ResChar elt : bid.getResourceList()){
ResCharCopy eltCopy = new ResCharCopy(elt);
resList.add(eltCopy.elt);
}
this.copy = new Bid(bid.getBidId(), bid.getPe(), resList);
}
}
So I want to know if there is any other solution to make a copy of "Bid" Object more effectively ?
I would suggest making a copy constructor for your Bid object (and not a specific class for copying), a Bid is made out of its fields and not methods, like so:
public class Bid {
int ID;
String description;
Object bidStuff;
// ...as before
public Bid(Bid bid) {
this.ID = bid.ID;
this.description = bid.description;
this.bidStuff = bid.bidStuff;
}
public static void main(String[] args) {
List<Bid> original = new ArrayList<>();
// ..populate it
List<Bid> copy = new ArrayList<>(original.size());
for (Bid b : original) {
copy.add(new Bid(b));
}
}
}
You can even make the copy constructor protected or package-protected if you don't want anyone else to mess around with making multiple copies of bids.
There is not. Even though some collections have "copy constructors", these constructors will copy the elements' references, they will not create new elements for you.
You can however "optimize" the list creation itself by submitting the size of the initial list to the constructor:
List<X> newList = new LinkedList<X>(oldList.size());