I am trying to add an element to an ArrayList using user input. The problem is when I try add something and ask to list it, it doesn't show it in the list.
I thought it was a problem with the read method, but I am not sure if there is anything wrong with it. The other thing was the fact that the method for adding an element wasn't in a loop, I tried using a loop but it still wasn't working.
There is a movie class with a constructor that has the parameters for title, year, genre, price and a toString method.
Expected result: After adding a movie, it should list the movie added.
Actual result: The add method asks for input but when I use the list method it doesn't list what I added.
Here is the full Kiosk and Catalogue class for more context.
new Catalogue().addMovie();
You are creating a new Catalogue each time you want to add a Movie, and you are never referencing it.
Instead, add all your movies to the same Catalogue:
private void addMovie(Catalogue c) {
c.addMovie();
}
private void listMovie(Catalogue c) {
c.listMovie();
}
that's because of the 'new' keyword. you need to use singleton 'Catalogue' object here.
class Kiosk {
private static Catalogue catalogue;
public Catalogue getCatalogue() {
if(Objects.isNull(catalogue)){
catalogue = new Catalogue();
}
return catalogue; //will return singleton catalogue object
}
private void addMovie() {
getCatalogue().addMovie();
}
private void listMovie() {
getCatalogue().listMovie();
}
}
In Kiosk you must keep an instance of your catalogue.
I don't know where you plan to create the Catalogue instance so added 2 constructors:
public class Kiosk {
private Catalogue cat;
public Kiosk() {
this(new Catalogue());
}
public Kiosk(Catalogue catalogue) {
this.cat=catalogue;
}
private void addMovie() {
cat.addMovie();
}
private void listMovie() {
cat.listMovie();
}
}
Related
In my project, in one of the classes (Adventure) I created an ArrayList and worked on it (add elements, delete others...)
This ArrayList is then passed as a parameter when creating an instance of another class (Player) inside Adventure.
Therefore I of course needed to created an ArrayList in Player and constructor, to catch the ArrayList sent from Adventure.
I'm not really sure, that all what i've done is correct. I'm getting the warning in Player Class:
This private field "createdObjects" is never assigned
Should i change smtg, or just ignore the warning ?
Here's the code :
public class Player {
private ArrayList<Objects> createdObjects;
public Player(ArrayList<Objects> createdObjects) {
//Originally i have many other elements in this constructor
// but i let only what concerns this arrayList
}
public ArrayList<Objects> getCreatedObjects() {
return createdObjects;
}
}
public class Adventure {
private ArrayList<Objects> createdObjects = new ArrayList<>();
public ArrayList<Objects> getCreatedObjects() {
return createdObjects;
}
// ...methods that will add/modify... the arraylist
public Player letsStart(){
Player player = new Player(createdObjects);
return player;
}
}
So basically im creating a list with a lot of information that i get from the user, and i need to display that "Estudiante" created on a list asside. So this is what i first tried, but it tells me that setListData is for arrays, so i tried other thing that i found that included the using .toArray(array) but that didnt work too.
Just to clarify what modelo is i copied this first code
public class VentanaEstudiante extends javax.swing.JFrame {
private Sistema modelo;
/**
* Creates new form VentanaEstudiante
*/
public VentanaEstudiante(Sistema unSistema) {
modelo = unSistema;
this.setSize(400, 280);
initComponents();
}
private void BotonCrearEstudianteActionPerformed(java.awt.event.ActionEvent evt) {
Estudiante unEst=new Estudiante(NombreEstudiante.getText(), Integer.parseInt(CedulaEstudiante.getText()),MailEstudiante.getText(), Integer.parseInt(NumeroEstudiante.getText()), Integer.parseInt(SemestreEstudiante.getText()));
modelo.agregarEstudiante(unEst);
ListaEstudiantesJ.setListData((modelo.getListaEstudiantes()).toArray());
Estudiante has a toString method, and the superclass, also does.
public String toString(){
return super.toString() + "Numero:" + this.getNumero() + "Semestre: " + this.getSemestre();
}
Here you have my lists and i only copied the listaEstudiantes methods because this are the ones im asking right now. This class Sistema, doesnt have any toString methods because i throught that this arraylist didnt needed one.
public class Sistema {
private ArrayList<Estudiante> listaEstudiantes;
private ArrayList<Docente> listaDocentes;
private ArrayList<Equipo> listaEquipos;
public Sistema(){
listaEstudiantes = new ArrayList<>();
listaDocentes= new ArrayList<>();
listaEquipos=new ArrayList<>();
}
public void agregarEstudiante(Estudiante unEstudiante){
listaEstudiantes.add(unEstudiante);
}
public ArrayList<Estudiante> getListaEstudiantes(){
return listaEstudiantes;
}
I need to use ArrayList in case you have something that may work better, i just need to use them
This whole project has a lot of showing Lists and sometimes i have to even let the user select things from them, something that i also dont know how to do but i dont know if i can ask more than one question here. The list is also going to need to refresh and all of that but i think i can handle that. Thanks
JList.setListData() has two variants, one expecting an array of elements, the other expecting a vector of elements.
Behind the scenes these two methods create an instance of an anonymous subclass of AbstractListModel and pass that instance to JList.setModel().
You can easily implement similar code for any List instance:
static <E> void setListData(JList<E> jList, List<? extends E> listData) {
jList.setModel(new AbstractListModel<E>() {
public int getSize() { return listData.size(); }
public E getElementAt(int i) { return listData.get(i); }
});
}
Say I've got a Java file with 500 custom objects of type Item. Now, say I want users to be able to add/remove any one of those objects to that list in the program. I want to try to avoid doing something like this:
public class Inventory {
public static ArrayList<Item> inv = new ArrayList<>();
public static void addItem1 {
inv.add(Item.Item1); //Pulling from Item class
} //addItem1()
public static void removeItem1 {
inv.remove(Item.Item1);
} //removeItem1()
public static void addItem 2 {
. . .
}
. . .
}
By doing that, I'd have to make an add and a remove function for every single item. There will be hundreds of items, so I sincerely hope there's a better way for the user to be able to do so from inside of the program. This would further be awful because of how it would require some massive nested switch statements to swap out everything.
Instead I'd hope to implement a single adder method and a single remover method, that could take the user's input (a String with the literal name of the Item they are trying to add), and somehow find/select the Item. Implementation thoughts?
How about using generic class ?
public class Inventory<T> {
public static ArrayList<Item> inv = new ArrayList<>();
public void addItem (T item){
inv.add((Item)item); // where item can be anything from Item.item1 to Item.item500
}
public void removeItem (T item){
inv.remove((Item)item);
}
In that case, to see if your item is in fact an item do something similar to this: System.out.println(item.getClass().getName()); //should return Item
Perhaps use:
public void setItem(Item item){
inv.add(item);
}
Then use the same concept for removal.
For my AP CompSci class, we're making a "Contacts" program to simulate using a virtual phonebook. The main class, Contacts is as follows.
public class Contacts extends ArrayList<Contact>
{
private ArrayList<Contact> contacts = new ArrayList<Contact>();
#Override
public boolean add(Contact c)
{
contacts.add(c);
Collections.sort(contacts);
return true;
}
public ArrayList<Contact> search(String name)
{
ArrayList<Contact> temp = new ArrayList<Contact>();
for(int i = 0; i<=contacts.size(); i++)
{
if(contacts.get(i).getName().equals(name))
{
temp.add(new Contact(name));
}
}
return temp;
}
}
As you can see, it extends ArrayList<Contact>. Contact is a simple object, composed of a String name and a 7-integer int num. The problem lies in the class ContactsFactory, where I loop through a text file to create a huge ArrayList of names.
public class ContactsFactory {
public static Contacts getContacts() throws FileNotFoundException {
String path = System.getProperty("user.dir");
Scanner s = new Scanner(new File(path + "\\src\\names.txt"));
Contacts contacts = new Contacts();
do {
contacts.add(new Contact(s.next()));
} while (s.hasNext());
s.close();
//print size to see anything added. It returns 0.
System.out.println(contacts.size());
return contacts;
}
}
However, when I implement the add() method for each name, not only does it seem not to add anything, but it returns no error. Even more interesting is that, as I found out when I put a print statement after every iteration, s.next() is no empty String. But the String(which experiences no issues being transferred from names.txt) is not added to contacts, and as a result, the ArrayList ends up empty with a size() of 0.
I think the error might be in the overridden Contacts.add() method, but I haven't been able to figure anything out. Can someone help me out? Thanks in advance.
I'm wondering why you extend ArrayList and additionally keep another copy of an ArrayList around. Besides the overwritten add (and size from azurefrog's answer), an ArrayList as well as the List interface offers a bunch of other methods - instead of overwriting all of them and delegating to the internal list, I would just rely on those methods and add the functionality I need:
public class Contacts extends ArrayList<Contact>
{
#Override
public boolean add(Contact c)
{
boolean result = super.add(c);
Collections.sort(this);
return result;
}
public ArrayList<Contact> search(String name)
{
// ...
}
}
By that you have a full-blown ArrayList and can extend it with what you need.
The other option is, to just kick out extends and just go for your own implementation of Contacts, utilizing the internal List as storage and not exposing it directly.
I think there is something wrong with your design.
I don't think you should extend ArrayList.
Because when you do it, your class IS an ArrayList, and also, you created an ArrayList object inside your class.
The thing is, when you called size, original ArrayList's size is being returned. Since you added the element to your ArrayList, the original is still empty.
You should use either delegation or inheritance, in this case you are mixing it both up.
Either implement java.util.List<Contact> (instead of extending ArrayList) and delegate every method call to the delegate (the class variable contacts)
OR
Remove the class variable contacts and use super.add() in your add method (instead of contacts.add()) and this instead of every other reference on contacts
I'm not sure how you read your file, but I seem to do just fine. In order to access the size of the contacts object in your factory, you need to call the 'size' method on the internal ArrayList instance variable, as opposed to calling on the 'contacts' object itself. In order to properly apply the 'size' method, it maybe that you need to override this method ('size') too.
Other than that, adding and retrieval seems fine. Check out the console output as well!
public class Contacts extends ArrayList<Contact>
{
private List<Contact> contacts = new ArrayList<Contact>();
#Override
public boolean add(Contact c)
{
contacts.add(c);
//Collections.sort(contacts);
return true;
}
#Override
public String toString()
{
return contacts.toString();
}
public List<Contact> getMyList()
{
return this.contacts;
}
public static void main(String[] args)
{
Contacts test=ContactsFactory.getContacts();
System.out.println(test.toString());
}
}
class ContactsFactory {
public static Contacts getContacts() {
String[] names={"A","B","C","D"};
int i=0;
Contacts contacts = new Contacts();
do {
System.out.println("Adding: "+names[i]);
contacts.add(new Contact(names[i]));
i++;
} while (i<names.length);
//print size to see anything added. It returns 0.
System.out.println(contacts.getMyList().size());
return contacts;
}
}
class Contact
{
String name;
#Override
public String toString()
{
return "Contact: "+this.name;
}
public Contact(String val)
{
this.name=val;
}
}
Output:
Adding: A
Adding: B
Adding: C
Adding: D
4
[Contact: A, Contact: B, Contact: C, Contact: D]
This class is where I want to call the arrays and set the arrays to empty within the parameters
public class ElectronicsEquipmentSupplier {
private int currentMonth;
private int currentYear;
private String rangeOfProducts;
private CustomerDetailsList details; //Contains the customer details array
private PurchaseOrderList pal; //Contains the purchase array
public ElectronicsEquipmentSupplier(int currentMonth, int currentYear,
String rangeOfProducts ) {
this.currentMonth = currentMonth;
this.currentYear = currentYear;
this.rangeOfProducts = rangeOfProducts;
}
}
This is the class where the array is created. It pulls information from a separate class called PurchaseOrder and then sets the list.
public class PurchaseOrderList {
private ArrayList<PurchaseOrder> purchaseCollection;
public PurchaseOrderList() {
purchaseCollection = new ArrayList<PurchaseOrder>();
}
The CustomerDetailsList class is essentially the same. Just not sure as to the best way to set the array to empty when called in the ElectronicsEquipmentSupplier.
Simply wrap the collection's own clear() method with a publicly-accessible method in your PurchaseOrderClass:
public class PurchaseOrderList {
private ArrayList<PurchaseOrder> purchaseCollection;
public PurchaseOrderList() {
purchaseCollection = new ArrayList<PurchaseOrder>();
}
//THIS IS THE IMPORTANT PART
public void clearPurchaseCollection() {
purchaseCollection.clear();
//You could also accomplish the same thing by reinitializing the list:
//purchaseCollection = new ArrayList<PurchaseOrder>();
}
}
Note however, that calling new PurchaseOrderList() already guarantees an empty purchaseCollection list, since you initialize it in the constructor that way.
So the only time you would need to call clearPurchaseCollection() is if you are reusing this object and want to clean it out first. Depending on the rest of your application, that may be necessary, but it may also just be simpler to throw away that instance and create a new PurchaseOrderList(). Totally depends on the situation.