How do I add an ArrayList to another ArrayList? - java

This makes my brain hurt...
I'd like to add multiple variables such as date and time to an arraylist, and add that arraylist to another arraylist holding different variables such as name and age.
Example: An ArrayList holds multiple accounts. Each account has an id, name, balance and transaction history. Each transaction has an id, date, time and transaction amount.
So the accounts ArrayList would contain: (int | String | double | ArrayList),
and the transactions ArrayList would contain: (int | Date | Time | double).
I'd appreciate it if you could help me understand how to do this, or offer a better solution.
EDIT:
I can't really show all my code because I'm using a model view controller which accesses a model and 4 views. I can try to describe what it does though.
Click "Create Account" button:
make a new account (using Account class)
set accountID = length of accounts ArrayList
set accountName = textbox input
set accountBalance = 0
create transactions ArrayList (using Transactions class)
add all to the accounts ArrayList.
Click "Deposit" button:
add TextBox input to accountBalance
set transactionID = length of transactions ArrayList
set transactionDate = current date
set transactionTime = current time
add all to selected account's transactions ArrayList

Do not use only lists for this, use concrete classes, i.e:
class Account {
String id;
String name;
float balance;
List<Transaction> history;
}
class Transaction {
String id;
Date date;
double amount;
}
And finally have a Map with your relevant data:
Map<Account, List<Transaction>> data = new HashMap<Account, List<Transaction>>();

Create an Account Class and a Transaction class. The Account class will hava as an attribute a list of transaction and when creating a List just declare it as following:
List<Account> myAccounts = new ArrayList<Account>();
and when you want to add an account just write :
myAccounts.add(new Account());

Related

Firebase: How to change child node value type from int to String?

A very basic backstory here, I am creating an attendance monitoring app for my final year project. This class opens when a student scans a generated QR Code. When they hit yes, I want it to add +1 to their Present value. However, I'm having some issues with this, since this code I'm using here:
rootRef.child("Users").child(uid).child("present").setValue(+1);
It changes the child node Present in the Database to an Integer type, which causes a crash in the Profile.class because it's trying to display it as a String, that is what I want.
How do I convert this value back to a string once it's been updated to reflect the student's attendance?
-Edit--------
Thanks for the quick response, how would I then go about changing everything to make it an int. This is my User.java which creates the variable fields for the Database:
package com.example.finalyearproject;
public class User {
//Initializing all of the variable names and values for the Database to upload to and pull from.
public String name, email, year, course, role, absences, present;
public User() {
}
public User(String name, String email, String year, String course, String role, String absences, String present) {
//These will be used to upload and pull data to and from the database, mainly for the Profile.class
this.name = name;
this.email = email;
this.year = year;
this.course = course;
this.role = role;
this.absences = absences;
this.present = present;
}
}
which causes a crash in the Profile.class because it's trying to display it as a String
Why not change the type of the field in the class to be a number rather than a string. When you want to increment a field with a numeric value, the type of the field should always be a number. There's no method in the String class that allows you to increment a char sequence.
Besides that, when it comes to incrementing values in the Realtime Database, most likely you should use ServerValue.increment(1) as explained in my answer from the following post:
How to save users score in firebase and retrieve it in real-time in Android studio
So in code that would be:
rootRef.child("Users").child(uid).child("present").setValue(ServerValue.increment(1));
Ok so I managed to figure this out for my specific project. It’s a bit basic and probably not very well optimised but it works lol.
I’ll leave it here for anyone who may have a similar issue. Thanks for all your guidance!
String present = userProfile.present;
int presentValue = Integer.parseInt(present);
presentValue = presentValue+1;
String finalPresentValue = Integer.toString(presentValue);
……
// Button OnclickListener
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
rootRef.child(“Users”).child(uid).child(“present”).setValue(finalPresentValue);

How to Iterate Datatable with type List<Class> in Cucumber

I have below feature file with Given annotation
Given user have below credentials
|user |password |
|cucumber1 |cucumber |
|cucumber2 |cucumber |
And i'm created below datamodel
public Class DataModel{
public string user;
public String password;
}
Trying to fetch data into the cucumber stepdefinition as below
Public Class stepdefinition {
#Given("^user have below credentials$")
Public void user_have_below_credintials(List<DataModel> dm){
//Iterator or foreach is required to fetch row,column data from dm
}
}
Please help me how can I Iterate object 'dm' to get row and column values
// The old way
for (int i = 0; i < dm.size(); i++) {
DataModel aDataModel = dm.get(i);
String username = aDataModel.user;
String password = aDataModel.password;
}
// A better way if java5+
for (DataModel aDataModel : dm) {
String username = aDataModel.user;
String password = aDataModel.password;
}
// another way if java8+
dm.forEach(aDataModel -> {
String username = aDataModel.user;
String password = aDataModel.password;
});
Note that the variables won't be available outside the loop with the way I wrote it. Just a demonstration of iterating and accessing the properties of each DataModel in your list.
A thing to keep in mind is that you're describing your list of DataModel objects as a data table. But it's not a table, it's simply a collection of values contained in an object, which you have a list of. You may be displaying it, or choosing to conceptualize it as a data table in your head, but the model that your code is describing isn't that, which means you aren't going to iterate through it quite like a table. Once you access a "row", the "columns" have no defined order, you may access them in any order you want to the same effect.

Constructing object

I have a query in constructing an object and storing it in database in json format.
Its in air domain industry. Need to construct an ojbect and store it in database in json format so the other applications can use the same object for various test automation scripts.
What i have done is i have created a class called PassengerDetails and inserted to station, from station etc., as below.
class PassengerDetails{
private String toStation;// Origin
private String fromStation;// destination
private String noOfAdults;
and getters and setters.
}
The passenger type also changes, like infants, companions etc., and i am not understanding how to handle it in class PassengerDetails. I have a guess like i have to add another class for PassengerType. Please correct me if i am wrong and suggest me how to add that passengertype details.
And I have created one ticket class (one ticket for each passenger, if 3 adults are there then 3 tickets and and three tickets are associated with one unique PNR). Here we have to store how the ticket is purchased, i mean by cash or credit card
class PaymentDetails{
private String creditCardType;
private String creditCardNo;
private String creditCardHolderName;
private String cash;
getters and setters.
}
We are having different payment types like Creditcard, cash, vouchers, refund amount etc., I am in confusion again how to handle this in the above PaymentDetails Class and how to link this class with TicketInformation and PassengerDetails
class TicketInformation{
private List<PassengerDetails> passengerDetails;
Getters and setters...
}
For multiple tickets, we have one PNR.
class PNRDetails{
List<TicketInformation> ticketInformationList = new ArrayList();
getters and setters.
}
Now i have a query like, if there is modification in flights or dates etc., new ticket will be issued. Now the question is how to store this new tickets and old tickets so that the user who retrieves the list of tickets can understand that there is a modification and hence there are new tickets and old tickets.
The other scenario is that if there is an addition of additonal passenger then not only the ticket changes but also the PNR changes, Now the question is i want to store both new and old PNRs and associated tickets.
For multiple PNR's how to write the class, do i have to write a class where it has List as instance variable. I messed up the code and i am in confusion. Could any one suggest better approach in modifications of code.
Here's an example on how to create an object and storing in json format:
var myObj = { "name":"John", "age":31, "city":"New York" };
var myJSON = JSON.stringify(myObj);
window.location = "demo_json.php?x=" + myJSON;
This is a very simple example of course.
Go through this website for more information and tutorials:
https://www.w3schools.com/js/js_json_intro.asp

How to search an array of objects and then update a part of the object in java?

I have an Array of objects. Each object is a customer record, which is the customer ID (int), first name (String), last name(String), and balance (double).
My problem is that i am not supposed to have duplicate customer records, so if they appear in the file twice, I have to just update their balance. I cannot figure out how to search the array to find out if i need to just update the balance or make a new record in the array.
I feel like i should do this in the get/setters, but i am not exactly sure.
edit: to clarify on "if they appear in the file twice, I have to just update their balance." I have a file i made in notepad which is supposed to be a customer list, which has all of their information. if the same customer shows up twice, say the following day to buy more stuff, i am not supposed to create a new object for them since they already have an object and a place in the array. instead, i am supposed to take the amount they spent, and add it to their already existing balance within their existing object.
edit2: i thought i would give you the bit of code i have already where i read in the values into the array. i based this off of the example we did in class, but we didn't have to update anything, just store information into an array and print it if needed.
public CustomerList(){
data = new CustomerRecord[100]; //i'm only allowed 100 unique customers
try {
Scanner input = new Scanner(new File("Records.txt"));
for(int i = 0; i < 100; ++i){
data[i] = new CustomerRecord();
data[i].setcustomerNumber(input.nextInt());
data[i].setfirstName(input.next());
data[i].setlastName(input.next());
data[i].setTransactionAmount(input.nextDouble());
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You shouldn't be using arrays in that case. A Set would be much more suitable as it, by definition, does not have duplicate entries.
What you need to do is to implement the equals() and hashCode() methods in your Customer class so they only use id (or id and name fields) but not balance.
If for some reason you need to use arrays you have two options:
sort the array and use binary search to find if the customer is there, this is nice if the array doesn't change much but you're doing a lot of updates
simply do a linear scan of the array, checking each entry to see if a given customer is already there, if so then update the balance, otherwise add it as a new entry
It would be something like:
public void updateOrAdd(Customer cst) {
boolean exists = false;
for(Customer existing : array) {
// !!! You need to implement your own equals method in the
// customer so it doesn't take into account the balance !!!
if(existing.equals(cst)) {
exists = true;
existing.updateBalance(cst.getBalance());
break;
}
}
if(!exists) {
// add the cst to the array
}
}
The difference is in runtime, the set solution will be constant O(1) on average (unless you incorrectly implement your hashCode() method).
Suppose you have a Customer array:
Customer[] customers = new Customer[size];
... // fill the array with data
Then you get a new customer object called newCustomer. You need to search for newCustomer in your array and, update it if it is already there, or add it if it's not. So you can do something like this:
// Return, if it exists, a customer with id equal to newCustomer.getId()
Optional<Customer> existingCustomer =
Arrays.stream(customers)
.filter(c -> newCustomer.getId().equals(c.getId()))
.findFirst();
if (existingCustomer.isPresent()) {
// update the customer object with newCustomer information as appropriate
Customer customer = existingCustomer.get();
// assuming you have an updateBalance() method
customer.updateBalance(newCustomer.amountSpent());
} else {
// if the customer is not in the array already, add them to the current position
customers[currentIndex] = newCustomer;
}

getting user defined object instances from resultset

I have a coding assignment in which I got stuck...
I have an Account table in which I need to select the unprocessed accounts; that's what I have done easy
now the assignment ask me to return each account in an Accounts array; which I got from query
So, how I could return an account array(how I could fill in the each unporcessed Account in resultset) into Accounts array to return from that already defined function which I am not allowed to chnge.
Is it any way that the resultset: return a single row it contain as an account instance?
we need to use Java 5 and not allowed to implement third party library
P.S
I have already tried:
Account account = (Account) rs.getObject("ID");` this has a classcast exception
and
Account account = (Account) rs.getObject("ID",Account.Class); this has also some other exception
I have also read about: Customized Type Mappings but I am not sure that even after doing all what it sugggest I would get the desired resuts
and this solution also involves creating customtype(in this case account) on databaselevel first which I am also not allowed to touch
as mentioned in some other answer
please share your exp.
The Class cast exception you are getting is expected because rs.getObject("ID") does not give an object that is of the class Account. You can create an array (or a List) of Account objects and populate it while iterating through the result set. (Assuming that you have all information of an account in a single row of the result set). Let us also assume the Account class as follows :
class Account {
int id;
String accountType;
String accountHolderName;
long accountBalance;
...
...
...
}
//Assuming the table columns that you are querying have these fields for each row:
AccountId | AccountType | AccountHolderName | AccountBalance | ...
101 | Checking | John | 100 | ...
//Populating the Account Objects
Account [] accArray = new accArray [sizeOfResultSet];
int i=0;
while (rs.next()){
Account current = new Account();
current.id = rs.getInt("AccountId");
current.accountType = rs.getString("AccountType");
current.accountHolderName = rs.getString("AccountHolderName");
...
...
...
}

Categories