getting user defined object instances from resultset - java

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");
...
...
...
}

Related

Trying to write a method in Java that will search a database list and return a Customer object, given a customerID

I am creating a customer manager application for a Java course. I have it separated as per the requirements into 3 packages. The first package has a class called Customer, which models a customer and it's instance variables, such as customerID. The second package is a customer database that includes an ArrayList. The third package is going to be a menu driven UI that will allow the user to choose between 4 options. Currently, I am stuck trying to write a method that will search through the list for a given customerID and return a Customer object.
In the customer database class, I am getting the customerID from the user within the method. Then, I am running a for loop that should traverse the method to see if the customerID is found. I am having issues on how to return a customer object if the id is a match.
public Customer searchCustomer(String customerID) {
System.out.println("Enter customer ID you want to find:");
customerID = scnr.next();
Customer c;
for (int i = 0, i < customerList.size(); i++ {
c = customerList.get(i);
if (customerList.get(i).equals(customerID) {
String foundID = customerID;
}
}
}
I want to return Customer c at the end of the method, but cannot figure out how to do this.
In the if statement one can just write return c. This will return the first Customer that matches. At the end of the method one can return null or throw an exception if the Customer wasn’t found.
You compare Customer object with CustomerId.
Change code to
if (customerList.get(i).getId().equals(customerID) {
return customerList.get(i);
}
A few of the potential mistakes you're making are:
Passing in an parameter to your method that you're not using. Either do the Scanner stuff outside of the method and then pass the ID to the method, or do the Scanner part in the method and have no parameters. The former approach is generally the preferred one, though.
Comparing the customer to a String. You need to compare the user-entered ID to the Customer object's ID field. The String the user enters will never be equal to the entire Customer object.
You're not returning anything from the method. Once you find the Customer you're looking for, you need a return statement.
Also, you can use Java's "enhanced for loop" to make the code a bit cleaner. Here's some code that assumes that your Customer objects use a String as their ID, and have a .getID() method on them to get their ID.
Here's some code that needs to search for a customer. This can be in another method.
System.out.println("Enter customer ID you want to find: ");
customerID = scnr.next();
Customer customer = searchCustomer(customerID);
And here's the search method that loops through the customerList
public Customer searchCustomer(String customerID) {
for(Customer customer : customerList) {
if (customer.getId().equals(customerID) ) {
return customer;
}
}
return null; // Or perhaps throw an exception.
}
Note that I'm making a lot of assumptions about how the other parts of your code that I haven't seen are structured, so you very probably will have to modify this code sample if you want to use it, but hopefully it puts you on the right track.

Cucumber Java Convert Data Table to Specific Type

I want to use a data table in my feature file and have the contents converted to a single specific type in the step definition. For Example I would like to be able to convert the following data table into a single instance of the User class.
Given the user is
| firstname | lastname | nationality |
| Roberto | Lo Giacco | Italian |
The User class:
class User {
String firstName;
String lastName;
Nationality nationality;
//getters / setters / etc
}
Step Definition:
#Given("^the user is$")
public void the_user_is(User user) {
this.user = user;
}
However when I run this I get the following error:
cucumber.runtime.CucumberException:
cucumber.runtime.CucumberException: Not a Map or List type: class example.User
The documentation suggests that it is possible to convert a data table to a single object.
Cucumber Transpose API Docs
However from inspecting the code it looks like it will always return a list. This code snippet is from cucumber/runtime/table/TableConverter.convert(DataTable dataTable, Type type, boolean transposed) :
Type itemType = listItemType(type);
if (itemType == null) {
throw new CucumberException("Not a Map or List type: " + type);
}
I know it works for a list:
#Given("^the user is$")
public void the_user_is(List<User> user) {
this.user = user.get(0);
}
but in my real world step (rather than this simplified example) there is only ever one object that needs created and I want to avoid using a list and then taking the first item.
There is an old issue regarding this problem in the cucumber-jvm repo on GitHub. It was recently labeled as a bug and is expected to be solved in release 2.1.
https://github.com/cucumber/cucumber-jvm/issues/741

How to print an arraylist's contents, not its location?

for(int i=0;i<ab.list.size();i++)
{
System.out.print( "Account: "+ab.ba.getCustomer().getAcct()+"\nDate:\n"+c);
}
ab is a Database object.
ba is a bank account object
from which you get getCustomer() and getAcct() methods to return a customer object and the method within it, getAcct(), the account number I'm trying to print for each location.
Now, it says this when I try and print it
java.lang.NullPointerException
Is that because list only returns pointers?
It seems that you are working in JPA and forgettten to add the MappedBy attribute in the one to many annotation
Or the entity is new
HTH

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;
}

How do I add an ArrayList to another ArrayList?

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());

Categories