[JAVA]preventing specific duplicate elements from being added to a custom object arraylist - class

so lets say i have an class called customer with first and last name and username and password
i have another class called bankaccounts with account number and banlance;
and i have an arraylist of customers;
and i have a txt file that i need to read
and it contains the same customer sometimes
how do i make it so that the when its reading if the (first name,lastname,username)are the same
the program wii not add the customer to the list but instead will only add the account to the
existing customer in the list.
sorry if my whole code is a mess but Im so lost in every where and I just want to get this part(the title) right at least please let me know if my question is inappropriate any where i will try my best to edit it
Bob, Mike, bobbmike, Ball!36Hi, 109001, Saving, 140.23, 0.05//good
Bob, Mike, bobbmike, Ball!36Hi, 109002, BasicChecking, 555.23//good
Mouse, Mickey, mickeymouse, MickCool890, ten, Saving, 89, 0.03//wrong numbber
Matt, Benjamin, jamimatt, Kit.24TT, 109201, InterestBearingChecking, 9000.00, 0.06//good
Keller, Helen, kel23hel, Poppins?89, 192911, Retirement, 11198.10//good
Mouse, Minnie, minniemouse, MinnCool19, 192922, Checking, 9000, 0.04//wrong type with interest
Keller, Helen, kel23hel, Poppins?89, 192912, InterestBearingChecking, 11198.10, 0.03//good
Tim, Mary, coolcats, Purr45??, 199122, BasicChecking, 201013.10//good
TheBuilder, Bob, bobbyNice18, 122101, Saving, 0.02//missing password, missing interest
class Customer{
protected String firstName;
protected String lastName;
protected String username;
protected String password;
protected ArrayList<BasicAccount> accounts;
public void setLastName(String ln){this.lastName=ln;}
public String getLastName(){return lastName;}
public void setFirstName(String fn){this.firstName=fn;}
public String getFirstName(){return firstName;}
public void setUsername(String un){this.username=un;}
public String getUserName(){return username;}
public void setPassword(String pw){this.password=pw;}
public String getPassword(){return password;}
public Customer(){}
public Customer(String f,String l,String u,String p) throws Exception{
this.username=f;
this.lastName=l;
this.username=u;
this.password=p;
}
public void addAccount(BasicAccount a){
this.accounts.add(a);
}
public void addAccount(String aType,float balance){
BasicAccount a=new BasicAccount(aType,balance);
}
}
class BasicAccount {
protected static int nextAvailableAccountNumber;
protected AccountType aType;
protected float balance;
protected int accountNum;
enum AccountType {BasicChecking, InterestBearingChecking, Saving, Retirement}
public BasicAccount(){};
public BasicAccount(String f,String l,String u,String p,int an,String type,float b){
}
public BasicAccount(Customer c,int a,String type,float b){
}
public BasicAccount(int a,String type,float b){
this.accountNum=a;
this.aType=AccountType.valueOf(type);
this.balance=b;
nextAvailableAccountNumber=accountNum+1;
}
public BasicAccount(String f,String l, String u,String p,String type,float b){
}
public BasicAccount(Customer c,String type,float b){
}
public BasicAccount(String type,float b){
this.accountNum=nextAvailableAccountNumber;
this.aType=AccountType.valueOf(type);
this.balance=b;
}
public static void main(String[] args)throws IOException {
ArrayList<Customer>cc=new ArrayList<Customer>();
Scanner k=new Scanner(System.in);
out.println("please enter the filename");
String filename=k.nextLine();
File inFile=new File(filename);
Scanner sc=new Scanner(inFile);
String error="";
ArrayList<String> errorLines=new ArrayList<String>();
while(sc.hasNext()){
String line=sc.nextLine();
try{
String []info=line.split(",");
if(info.length==7){
if(info[5].equals("BasicChecking")||info[5].equals("Retirement")){
Customer c=new Customer(info[0],info[1],info[2],info[3]);
BasicAccount act=new BasicAccount(c,Integer.parseInt(info[4]),info[5],Float.parseFloat(info[6]));
String [] user={c.firstName,c.lastName,c.username,c.password};
**for(Customer x:cc){
if(x.contains(c.getFirstName())&&c.getLastName()%%c.getUserName){
x.addAccount(act);
}
else{
c.addAccount(act);
cc.add(c);
}
}**//so if the customer object in the array list contains the same information from the
new Customer c it will only add the account to the x but if its not i will add to c and add
c to the arraylist but this doesn't work
}
else{
//error+="\n Wrong.";
//out.println(error);
}
}
}
catch(Exception e){
error+="\n wrong";
errorLines.add(line);
out.println("wrong data");
}
}
out.println(error);
if(errorLines.size()==0){}
else{
out.println(errorLines);
}
out.println(errorLines);
}
}
Main.java:277: error: cannot find symbol
if(x.contains(c.getFirstName())&&c.getLastName()){
^
symbol: method contains(String)
location: variable x of type Customer
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 error
sorry if my whole code is a mess but Im so lost in every where and I just want to get this part(the title) right at least please let me know if my question is inappropriate any where i will try my best to edit it

Related

Interaction between two classes

I want to know the best way to "share" or have access to attributes between 2 classes like this :
class A {
public A() {
B myClassB = new B();
}
int attributeA;
}
Class B {
int foo() {
// I want to have something like : return attributeA;
}
}
I hope that it's clear. If someone has a better way to ask the question let me know 'cause I really don't know how.
Thanks.
I would say by encapsulation you could share the fields (attributes) between classes. It is a fundamental OOP concept which helps a programmer to modify the already implemented code without breaking the code of others who use the fields.
Consider the below example (Java)
public class Person{
public String name = "John";
public int age = 25;
}
Sharing Person class's attributes with another class
public class EncapTest {
public static void main(String[] args) {
Person p = new Person();
p.name = "Tom";
p.age = 20;
System.out.println(p.name);
System.out.println(p.age);
}
}
The above approach is bad way to share(access) attributes between classes because any one can change the fields because they are public. So when you change them, they get changed for everyone (even for those who didn't want). It is like you're breaking the code of others.
See the below example which uses encapsulation
public class Person{
private String name;
private int age;
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age = age;
}
public int getName() {
return age;
}
}
Sharing Person class's attributes with another class
public class EncapTest {
public static void main(String[] args) {
Person p = new Person();
p.setName("Tom");
p.setAge(20)
System.out.println(p.getName());
System.out.println(p.getAge());
}
}
By making the attributes private and accessing them using the getters and setters methods, you are hiding the attributes with in the class. So whenever you set the attributes in another class, you're not breaking other programmers' code.

How to use set , get in gwt shared folder

I have a class select in gwt shared folder with some set and get function like..
public class Select implements Serializable {
private static final long serialVersionUID = 1L;
String userid=null;
String name=null;
/******************Set********************/
public void setId(String userid) {
this.userid=userid;
}
public void setName(String name) {
this.name=name;
}
/******************get*************************/
public String getId() {
return userid;
}
public String getName() {
return name;
}
now I called setid() and getid() from server,its working . but when i am calling getid() from client, its returning me a null value please some one help me ...
my client side code is ...
greetingService.select(new AsyncCallback<String>()
{
Select sel=new Select();
public void onSuccess(String result) {
System.out.println("client..id"+sel.getId());
});
sel.getid() is returning null because its not being set by anything. You are simply calling new Select() and creating a new Select object on the client. If you want to retrieve the Select object with data in it form the server you need to pass it as the result parameter of the AsyncCallback callback via an RPC service, like so:
greetingService.select(new AsyncCallback<Select>() {
public void onSuccess(Select result) {
// Do what you want with the Select object returned via server
}
public void onFailure(Throwable caught) {
System.out.println("Call failed " + caught.getMessage());
}
});
Assuming you have set up the RPC service properly, you will handle the server end as a regular method:
public class GreetingServiceImpl extends RemoteServiceServletImpl {
public Select select() {
Select select = new Select();
select.setId(1);
return select;
}
}
You may find this tutorial helpful http://www.gwtproject.org/doc/latest/tutorial/RPC.html

How to implement LeafValueEditor<Address>

I am trying to understand how to correctly implement a LeafValueEditor for a non immutable object. Which of the two way is correct, or should something else be used?
public class Address {
public String line1;
public String city;
public String zip;
}
Option 1:
public class AddressEditor implements LeafValueEditor<Address>
{
private String line1;
private String city;
private String zip;
private Address address;
public void setValue(Address value)
{
this.line1 = value.line1;
this.city = value.city;
this.zip = value.zip;
this.address = value;
}
public Address getValue()
{
this.address.line1 = this.line1;
this.address.city = this.city;
this.address.zip = this.zip;
return this.address;
}
}
Option 2:
public class AddressEditor implements LeafValueEditor<Address>
{
private String line1;
private String city;
private String zip;
public void setValue(Address value)
{
this.line1 = value.line1;
this.city = value.city;
this.zip = value.zip;
}
public Address getValue()
{
Address a = new Address();
this.a.line1 = this.line1;
this.a.city = this.city;
this.a.zip = this.zip;
return a;
}
}
Probably neither, though both technically could work.
A LeafValueEditor is an Editor for leaf values - that is, values that don't generally contain other values. Usually a text or date or number field that would be visible on the page is the leaf editor, and those leaf nodes are contained in a normal Editor.
In this case, it could look something like this:
public class AddressEditor extends Composite implements Editor<Address> {
// not private, fields must be visible for the driver to manipulate them
// automatically, could be package-protected, protected, or public
protected TextBox line1;//automatically maps to getLine1()/setLine1(String)
protected TextBox city;
protected TextBox zip;
public AddressEditor() {
//TODO build the fields, attach them to some parent, and
// initWidget with them
}
}
See http://www.gwtproject.org/doc/latest/DevGuideUiEditors.html#Editor_contract for more details on how this all comes together automatically with just that little wiring.

RequestFactory ValueProxy class with embedded List of another ValueProxy not visible in response on client

I have a requestfactory service request that returns a List<> of RoleProxy. The RoleProxy contains a List<> of PermissionProxy. I can see the data coming back from the server. I can see it in the data that is being parsed by the AutoBean decode. But the response RoleProxy in the onSuccess method does not have any data in it's List<>.
Here is the RoleProxy
#ProxyForName("com.ihg.atp.schema.crs.revenue.sbrpa.datatypes.v1.RolesType")
public interface RoleProxy extends ValueProxy {
public int getId();
public void setId(final int id);
public String getName();
public void setName(final String name);
public List<PermissionProxy> getPermissions();
public void setPermissions(final List<PermissionProxy> permissions);
}
The Permissions Proxy
#ProxyForName("com.ihg.atp.schema.crs.revenue.sbrpa.datatypes.v1.PageType")
public interface PermissionProxy extends ValueProxy {
public String getPageIndex();
public void setPageIndex(final String pageIndex);
public String getAccessType();
public void setAccessType(final String accessType);
}
And the calling routine
RolesContext ctx = requestFactory.rolesContext();
ctx.getAllRoles().with("permissions").fire(new Receiver<List<RoleProxy>>() {
#Override
public void onSuccess(List<RoleProxy> response) {
#SuppressWarnings("unused")
List<PermissionProxy> perms = response.get(0).getPermissions();
// Here perms is an empty list instead of the data that was sent
}
});
Does anyone have an idea of what is happening here? I have done similar things in the past with EntityProxies.
On Edit: Added link to response body.

POJO information lost during RPC call (GWT)

I am having issues with RPC calls and GWT. Essentially, I have a Person class (common code between client and server) that is created in the client side web code, sent to the server code via an RPC call, and then saved to a DB (OrientDB). I have verified that the following work:
RPC call - I am able to send info to the server and retrieve info from the server
save to DB - have verified that a Person object is saved to the DB
Where I am having issues is the transfer of the POJO from the client to the server. I have verified that the POJO's properties are intact right before it is sent to the server, however, the object passed to the server contains null values for all properties. Essentially, the class is transferred but the information is not. It then saves to the DB, but obviously without any relevant information contained within it.
I will copy what I feel is relevant below, please let me know what else I can provide to make this problem easier to identify. Note these are still in a testing state, so mind the comments :)
Any idea why my POJO's information is being lost in translation?
Person object, followed by the abstract class it inherits from:
public class Person extends org.matesweb.shared.AbsPerson implements Serializable
{
#Id
private String id; // DON'T CREATE GETTER/SETTER FOR IT TO PREVENT THE CHANGING BY THE USER APPLICATION,
// UNLESS IT'S NEEDED
//sets new user details
public void setPerson(String fIrstName, String mIdInit, String lAstName, String email, String password)
{
firstName = fIrstName;
middleInitial = mIdInit;
lastName = lAstName;
}
/*getter and setter methods - required for every
* field due to restrictions imposed by OrientDB*/
public Object getId()
{
String tmp;
tmp = id.toString();
return tmp;
}
//end class
}
public class AbsPerson implements Serializable
{
String firstName;
String middleInitial;
String lastName;
// public sys.Login login;
public org.matesweb.shared.Group[] groups;
private org.matesweb.shared.Purchase[] purchases;
/*this method adds a new purchase to the purchases variable*/
/* public void addPurchase(float price, String description)
{
people.Purchase newPurchase = new people.Purchase(login, price, description);
}
*/
/*adds a person to a group by comparing the passed in group ID and PWD*/
public void addGroup(String groupID, String groupPWD)
{
//compare group ID with group PWD to add a user to the group
}
/*getter and setter methods - required for every
* field due to restrictions imposed by OrientDB*/
public String getFirstName()
{
return firstName;
}
public void setFirstName(String name)
{
firstName = name;
}
public String getMiddleInitial()
{
return middleInitial;
}
public void setMiddleInitial(String midInit)
{
middleInitial = midInit;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String ln)
{
lastName = ln;
}
/*
public sys.Login getLogin()
{
return login;
}
public void setLogin(sys.Login log)
{
login = log;
}
*/
public org.matesweb.shared.Group[] getGroups()
{
return groups;
}
public void setGroups(org.matesweb.shared.Group[] gro)
{
groups = gro;
}
public org.matesweb.shared.Purchase[] getPurchases()
{
return purchases;
}
public void setPurchases(org.matesweb.shared.Purchase[] purch)
{
purchases = purch;
}
}
Service
package org.matesweb.client;
import com.google.gwt.user.client.rpc.RemoteService;
import com.google.gwt.user.client.rpc.RemoteServiceRelativePath;
import org.matesweb.shared.Person;
#RemoteServiceRelativePath("peopleService")
public interface PeopleService extends RemoteService {
//test services
String stringTest(String outgoingString);
Person getPerson(String persId);
//production services
String savePerson(Person p);
}
ServiceAsync
import com.google.gwt.user.client.rpc.AsyncCallback;
import org.matesweb.shared.Person;
public interface PeopleServiceAsync
{
//tests
void stringTest(String outgoingString, AsyncCallback<String> incomingString);
void getPerson(String persId, AsyncCallback<Person> retPerson);
//production services
void savePerson(Person p , AsyncCallback<String> st);
}
ServiceImpl call for this particular method:
//production calls
#Override
public String savePerson(Person p) {
String st = ioObj.saveObj(p);
if(st.equals("Success")){
return "Your information has been saved successfully!";
} else{
return "Something has gone wrong on our end... Sorry! Error:<br /> " + st;
}
}
and finally, the call itself
private static void savePerson(Person p)
{
// Initialize the service proxy.
if (peopleSvc == null) {
peopleSvc = GWT.create(PeopleService.class);
}
//resets status
st="";
// Set up the callback object.
AsyncCallback<String> callback = new AsyncCallback<String>() {
#Override
public void onFailure(Throwable caught) {
st = caught.getMessage();
Label stLabel= new Label(st);
personTable.setWidget(3,1,stLabel);
}
#Override
public void onSuccess(String result) {
st = result;
HTML stLabel= new HTML(st);
joinPanel.add(stLabel);
}
};
// Make the call to the people service.
peopleSvc.savePerson(p, callback);
}
I was able to fix this issue by implementing GWT's IsSerializable interface. I also removed the Serializable interface from the Person class and let it inherit IsSerializable from the abstract class it inherits from.