Having trouble with the arraylist get method - java

Basically, I have an ArrayList of BudgetItem objects (BudgetItem being a class I made). Each BudgetItem has three instance variables, price, name, and quantity with setters and getters for each. I am adding each BudgetItem to the ArrayList one at a time, each with different information in the price variable. When I go to print out any price element of the ArrayList, using the get method, the console will always print the last price that was entered. Below, I will paste some sample code to help:
public class Register {
private ArrayList<BudgetItem> register = new ArrayList<BudgetItem>();
public Register(double[] price) {
//Creates a register ArrayList with specified number of
//elements and populates it with BudgetItems that contain
//the data in the price array entered in the declaration.
BudgetItem bi = new BudgetItem();
for(int i = 0; i<price.length; i++) {
bi.setPrice(price[i]);
register.add(bi);
if(i=0) { //This if statement is for debugging.
System.out.println(register.get(i).getPrice());
}
}
//This is also for debugging.
double i = register.get(0).getPrice();
System.out.println(i);
}
}
Through my debugging efforts I found that the problem is with the get method in ArrayList. No matter what I do it returns the last instance of price that was entered. My question is why won't the get method return the specified element?

Well the problem is that you always modify the same BudgetItem object.
Try :
for(int i = 0; i<price.length; i++) {
BudgetItem bi = new BudgetItem(); <-- move it inside the for loop
bi.setPrice(price[i]);
register.add(bi);
}

You are only adding a single BudgetItem and setting and resetting its price. You need to add new BudgetItems and set their prices accordingly.

Add BudgetItem bi = new BudgetItem(); inside for loop

Related

How to map ArrayList elements with specific values and then print it

ArrayList<Integer> companiesId = new ArrayList<>();
int numberOfCompanies = 10; // Just for example
...
float profit;
Scanner input = new Scanner(System.in);
for(int i = 0; i < numberOfCompanies; i++) {
int companyId = input.nextInt();
if (!companiesId.contains(companyId)) {
companiesId.add(companyId);
}
if (companiesId.get(i) == 1) {
profit = 1000;
} else if (companiesId.get(i) == 2) {
profit = 2000;
}
}
Now I want to print all the companyIds from the ArrayList with the profit entered for each id, but I don't know how to do it with the ArrayList.
It should be:
1 1000
2 2000
...
You cannot do what you ask because part of the information you need to print (profit) is lost. What you need to do first is to create a class that holds a company ID and the profits. With the new version of Java, you can create a record that will hold such information. A Java Record is nothing more than a POJO that is identified with that new keyword (record) and does not require you to create all the boilerplate code. Your record class will look something like this:
public record CompanyRecord(int companyID, float profit) {
}
You don't even need to override toString(). That is, unless you want to print the contents of the record in a different way than the default. Then, you will need to create a list of CompanyRecord objects:
ArrayList<CompanyRecord> companies = new ArrayList<>();
Then, you can do whatever you need. For example, I created this simple demo that create a list of 10 company records and uses the loop counter to set the company ID and as a multiplier for the profits. Lastly, it prints out the record to the console.
public class CompanyRecordDemo {
public static void main(String[] args) {
ArrayList<CompanyRecord> companies = new ArrayList<>();
float profit = 1000.0f;
for (int i = 1; i <= 10; i++) {
CompanyRecord rec = new CompanyRecord(i, profit * i);
companies.add(rec);
System.out.println(rec);
}
// do whatever you need with the list...
}
}
The output of this small program is:
CompanyRecord[companyID=1, profit=1000.0]
CompanyRecord[companyID=2, profit=2000.0]
CompanyRecord[companyID=3, profit=3000.0]
CompanyRecord[companyID=4, profit=4000.0]
CompanyRecord[companyID=5, profit=5000.0]
CompanyRecord[companyID=6, profit=6000.0]
CompanyRecord[companyID=7, profit=7000.0]
CompanyRecord[companyID=8, profit=8000.0]
CompanyRecord[companyID=9, profit=9000.0]
CompanyRecord[companyID=10, profit=10000.0]
This is probably the simplest way to accomplish what you need. You will need to use Java 14 or later to make use of Java Records, but I recommend you use the latest version.
UPDATE: One important thing to note is that Java records are immutable. So, they have no setters (mutator methods). You will have to set the values through the constructor and values cannot be changed afterwards. You can access (get) the property values by calling a method that has the same name as the field. For example, the getter method for profit is profit(). For example rec.profit().

Add elements with arguments in an array with java

I want to add a new element that has several arguments in an array. I know how to add with just one argument, but with more i don't know.
My code is:
private Calculate[] calculation;
public Element(int numElements) {
calculation = new Calculate[numElements];
}
public void addElement(Date elementDate, double price, ElementType type) {
int numElements = elements.length;
int i = 0;
if (i < numElements) {
Calculate[i] = calculation.elementDate;
Calculate[i] = calculation.price;
Calculate[i] = calculation.type;
i++;
}
}
Calculate[i] = calculation.elementDate;
Calculate[i] = calculation.price;
Calculate[i] = calculation.type;
You shouldn't assign to the same array index 3 times. You're overriding what you've just set.
Try this (Calculate should have a constructor):
Calculate[i] = new Calculate(elementDate, price, type);
You're also maintaining an index i, but you're not looping over anything. i is just incremented from from zero to one and is not really used (apart from an almost useless conditional check).
I suggest you read over a beginners Java tutorial. You seem to be missing a lot of the fundamentals, and Stack Overflow is not a place where we should have to show you how to write a for-loop. It's well-documented and demonstrated in a tonne of tutorials already.
I assume Calculate is a class defined else where with a constructor
There is a couple of issues in this piece of code:
You want to update the array, but specify array. Calculate[] is the array type. The name if the array is calculation. The other thing is that you are trying to access calculation.elementDate etc. but since that is an array, it does not have the field elementDate. I assume your Calculate class has that field. Also, you are not applying a loop. So currently your code will only update the array on index 0.
My code:
public void addElement(Date elementDate, double price, ElementType type) {
for(int i = 0; i < elements.length; i++) { // for loop over all elements in your array
Calculate calculate = new Calculate(elementDate, price, type) // I assume this constructor is available to initialize the Calculate object
calculation[i] = calculate;
}
Hope this helps.

Method for printing Arraylist returns []

I'm trying to make a booking system for a hotel using the MVC dp. I have a class with a fixed arraylist of rooms (from 1-25) inside the model and class in which I have the showAvailableRooms method in the controller package . I'm asking my View to print out the available rooms but the only thing it prints out is two square brackets ([]).
P.S. The get OccupiedRoom is another method I have in my bookinglist class (model). It checks if the dates you pass it as arguments are a problem to already existing bookings,if it is then it checks if the room is already in that occupied list and if it isn't it adds it to the list.
public void showAvailableRooms(MyDate arrivaldate, MyDate departuredate) {
ArrayList<Room> availablerooms = new ArrayList<Room>();
for (int i = 0; i < 25; i++) {
for (int j = 0; j < l.getOccupiedRoom(arrivaldate, departuredate).size(); j++) {
if (h.getRoom(i) != l.getOccupiedRoom(arrivaldate, departuredate).get(j)) {
availablerooms.add(h.getRoom(i));
} else if (l.getOccupiedRoom(arrivaldate, departuredate).size() == 0) {
System.out.println(h.getAllRooms());
}
}
System.out.println(availablerooms);
}
As i said in comment [] means your list is empty.
you add elements to availablerooms only in your inner loop, but if l.getOccupiedRoom returns you empty list, then code inside inner loop won't be executed, and no empty rooms will be added.
two square brackets ([]). Means that availablerooms doesn't have any entry. Either there are no available rooms, or it isn't getting populated correctly. Please check your logic.

Clearing a dropdown counter in Java?

I need to clear all the fields in several arrays to re-load a new template to parse. I currently set up a function to clear all the relevant array lists and counts. Those are working fine except I am having a hard time clearing out obrDD inside my clearMicroArray() function.
Here is my current code (without logic to clear obrDD). How can I clear the dropdown information inside my function?
static void clearMicroArray() {
fullMicroArray.clear();
int returnSize = fullMicroArray.size();
System.out.println("size of full array" + returnSize);
obrCount = 0;
fileRowCount = 0;
// obr List
obrList.removeAll(obrList);
obxList.removeAll(obxList);
};
// Populating the OBR number in dropdown
public static void populateOBRDropdown(JComboBox<String> obrDD) {
for (int i = 0; i < fullMicroArray.size(); i++) {
if (fullMicroArray.get(i).substring(0, fullMicroArray.get(i).indexOf("|")).equals("OBR")) {
i++;
obrCount++;
obrDD.addItem("OBR " + obrCount);
}
}
}
obrDD is a JComboBox object that you pass into populateOBRDropdown. Your clearMicroArray method, however, also needs obrDD as an input in order for you to do anything with it. Once you pass a reference to the JComboBox, you can call removeAllItems or removeItem from clearMicroArray.

Getting the next Value in a ArrayList(Not working)

I'm trying to get the next value in a specific arraylist every time a user presses a button (using Swing).
This is my attempt at it:
private void BNextActionPerformed(java.awt.event.ActionEvent evt) {
int i = 0;
Parse p = new Parse();
temp = p.getTemp();
temp2 = p.getTemp2();
temp3 = p.getTemp3();
if (CBUniversities.getSelectedIndex() == 0) {
LNumStudents.setText("Number of students: " + temp);
Student s = p.getMacList().get(i+1);
jTextField2.setText(s.getFirstName());
TLastName.setText(s.getSurName());
jTextArea1.setText(s.getAddress());
i++;
}
}
Where Parse is a class, containing getter methods for 3 integerstemp,temp2,temp3, and a getter for an ArrayList.
Student s is an object of the Student class, where every student has a firstname, surname and address (initialized in a constructor).
When this if statement is executed it displays a students info in the specified fields, however, this only works for the first two students. After that, the i value never seems to increase?
I tried to place a println check to see it's value during the if statement, but it only changes once, oddly enough.
I also tried to make this into a for loop, yet the value again only seems to change once (of i).
Parse has this getter method I'm using
public ArrayList<Student> getMacList() {
return mac;
}
Also CBUniversities is a variable as such:
private javax.swing.JComboBox CBUniversities;
I'm not sure what's gone wrong here, any ideas?
You declared i within the scope of a method, so every time your method executes it reinitializes i.
Instead, declare an instance variable by putting private int i = 0; outside of your method, but still within the class scope.

Categories