it's been a while since I've done some java coding.
I need to build an application for a business which requires automation (part of a workshop), which is however irrelevant to my question...
I'm stuck on the line : customerList.add(customer); //(part of the addCustomer method in the WCIA class)
Also it's the first time I'm told to "Assign return value to new Variable" as part of an error, so not too sure what that means.
Code: Main
import java.util.ArrayList;
public class WCIA {
private final ArrayList customerList = null;
public static void main(String[] args) {
short s =002;
Customer arno = new Customer();
arno.setName("Arno");
arno.setId(s);
arno.setEmail("arnomeye#gmail.com");
arno.setAddress("Somewhere");
arno.setPhoneNum("0727855201");
System.out.printf("%s",arno.getEmail());
WCIA wcia = new WCIA();
wcia.addCustomer(arno);
wcia.displayCustomers();
}
public void addCustomer (Customer customer)
{
customerList.add(customer); // <---Problem over here
}
public void displayCustomers()
{
for(int x=0;x<customerList.size();x++)
{
Customer cus = (Customer) customerList.get(x);
cus.DisplayCustomer();
}
}
}
Code: Customer class:
public class Customer {
private short id;
private String name;
private String email;
private String phoneNum;
private String address;
public Customer()
{
System.out.println("Class initiated");
}
public void DisplayCustomer()
{
System.out.append("Name : "+ name+"\n");
System.out.append("ID : "+ id+"\n");
System.out.append("Email : "+ email+"\n");
System.out.append("Phone Number : "+ phoneNum+"\n");
System.out.append("address : "+ address+"\n");
}
public void setId(short id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setEmail(String email) {
this.email = email;
}
public void setPhoneNum(String phoneNum) {
this.phoneNum = phoneNum;
}
public void setAddress(String address) {
this.address = address;
}
public short getId() {
return id;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPhoneNum() {
return phoneNum;
}
public String getAddress() {
return address;
}
}
You need to instantiate your ArrayList before you can assign elements to it. You're probably getting a NullPointerException, is my guess.
Change this line:
private final ArrayList customerList = null;
to
private final ArrayList customerList = new ArrayList();
Should solve at least this problem. I did not read the rest of your code so I'm not sure if other problems exist.
customerList is null and never initialized. Create an object of type ArrayList and assign it to that variable before you try to add to it.
You should declare the List with an explicit definition of the type of its elements (parametrized list):
private final List<Customer> customerList;
This way you can get rid of casting to Customer in:
Customer cus = customerList.get(x);
Finally, as good practice, initialize it in the constructor:
public WCIA()
{
customerList = new ArrayList<>();
}
Related
(I'm a beginner so this may sound obvious/lack information.) I have an ArrayList of attributes for different pets including attributes such as their given-name, common-name, the price of the animal, sex, date bought and date sold. this information is generated from a separate class that adds an array of information to an array of arrays of the already existing list of animals. Essentially, I want to send the array to another class (called Pets) so it can then be added to the array of arrays. I understand this may sound confusing but this is the only way I can word it, I can clarify anything if needed. Any help would be great as I'm really stuck and can't work out how to send it. This is the code that generates my values in the array (using text-boxes to input the information).
public void actionPerformed(ActionEvent e) {
ArrayList<String> NewanimalArr = new ArrayList<>();
String givenName = txtGivenname.getText();
String commonName = txtCommonName.getText();
String priceOf = txtPrice_1.getText();
String sexOf = txtSex.getText();
String colourOf = txtMaincolour.getText();
String dateOfA = txtArrivaldate.getText();
String dateSold = txtSellingdate.getText();
NewanimalArr.add(givenName);
NewanimalArr.add(commonName);
NewanimalArr.add(priceOf);
NewanimalArr.add(sexOf);
NewanimalArr.add(colourOf);
NewanimalArr.add(dateOfA);
NewanimalArr.add(dateSold);
System.out.println(NewanimalArr);
}
});
this will then print information generated that is entered for example:
[alex, Dog, 40.50, Male, Brown, 14/04/2015, 14/12/2016]
how do I then send this data to another class
Option one Constructor Injection:
public class Foo {
List<String> actionPerformed(ActionEvent e) {
List<String> newanimalArr = new ArrayList<>();
.....
return newanimalArr
}
...
public class Pets {
private final List<String> array;
public Pets(final List<String> array) {
this.array = array;
}
void bar() {
System.out.println(this.array);
}
}
....
public static void main(String[] args) {
Foo foo = new Foo();
Pets pets = new Pets(foo.actionPerformed( new ActionEvent() ) );
pets.bar();
}
Option two Getter-Setter Injection:
public class Foo {
private final List<String> newanimalArr;
public Foo() {
this.newanimalArr = new ArrayList<>();
}
public void actionPerformed(ActionEvent e) {
.....
}
public List<String> getNewanimalArr() {
return new ArrayList<String>(newanimalArr);
}
}
...
public class Pets {
private List<String> array;
public Pets() {
this.array = Collections.<String>emptyList();
}
public void setArray(final List<String> array) {
this.array = array;
}
public void bar() {
System.out.println(this.array);
}
}
....
public static void main(String[] args) {
Foo foo = new Foo();
foo.actionPerformed( new ActionEvent() );
Pets pets = new Pets();
bar.setArray( foo.getNewanimalArr() );
pets.bar();
}
See also Dependency Injection Patterns
Create a class definition of Pet, using instance variables for the fields. In Java it is custom to create a setXyz and a getXyz for each xyz field. You can also create a constructor in which you pass all the values and assign them to the fields, this minimizes the risk of fields not being filled in.
The initial ArrayList you are creating doesn't add that much use, it is easier to create the Pet instances directly:
List<Pet> newArrivals = new ArrayList<>();
// get data from view fields and if necessary transform them to other objects such as:
LocalDate arrivedOn = LocalDate.parse(txtArrivaldate.getText(), DateTimeFormatter.ofLocalizedDate(FormatStyle.FormatStyle);
// create and add a new Pet object to the list
newArrivals.add(new Pet(.....));
public class Pet {
public enum Gender {
FEMALE, MALE
}
private String givenName;
private String commonName;
private double price;
private Gender gender;
private String color;
private LocalDate arrivedOn;
private LocalDate soldOn;
public Pet() {
}
public Pet(String givenName, String commonName, double price, Gender gender, String color, LocalDate arrivedOn,
LocalDate soldOn) {
super();
this.givenName = givenName;
this.commonName = commonName;
this.price = price;
this.gender = gender;
this.color = color;
this.arrivedOn = arrivedOn;
this.soldOn = soldOn;
}
public String getGivenName() {
return givenName;
}
public void setGivenName(String givenName) {
this.givenName = givenName;
}
public String getCommonName() {
return commonName;
}
public void setCommonName(String commonName) {
this.commonName = commonName;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public LocalDate getArrivedOn() {
return arrivedOn;
}
public void setArrivedOn(LocalDate arrivedOn) {
this.arrivedOn = arrivedOn;
}
public LocalDate getSoldOn() {
return soldOn;
}
public void setSoldOn(LocalDate soldOn) {
this.soldOn = soldOn;
}
}
I have a Class Foo that has a Constructor that sets name and id.
In another Class I have a List<String> of messages where I can extract the name and id.
I'm able to successfully set the Constructor by looping through the list using regular foreach loop. How do I achieve this using Stream Java 8 or Lambda or Method References
public class ConstructorTest {
public static void main(String[] args) {
List<Foo> fooList = new ArrayList<Foo>();
List<String> userList = new ArrayList<String>();
userList.add("username1_id1");
userList.add("username2_id2");
//I want to replace the below foreach loop with stream/lambda/methodreferences
for (String user : userList) {
Foo foo = new Foo(getName(user), getId(user));
fooList.add(foo);
}
}
private static String getName(String user) {
return user.split("_")[0];
}
private static String getId(String user) {
return user.split("_")[1];
}
}
Foo Class:
public class Foo {
public Foo(String name, String id) {
this.name = name;
this.id = id;
}
private String name;
private String id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
How about this?
userList.stream().map(user -> new Foo(getName(user), getId(user)).forEach(userList::add)
Or this
userList.forEach(user -> userList.add(new Foo(getName(user), getId(user))))
I've got the following question. I got a little application which saves payments, dates and persons inside a database. Now I got the following POJO class:
public class Payment implements Serializable {
private int id;
private double payment;
private Date datum;
private String usage;
private String category;
private int importance;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public double getPayment() {
return payment;
}
public void setPayment(double payment) {
this.payment = payment;
}
public Date getDatum() {
return datum;
}
public void setDatum(Date datum) {
this.datum = datum;
}
public String getUsage() {
return usage;
}
public void setUsage(String usage) {
this.usage = usage;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public int getImportance() {
return importance;
}
public void setImportance(int importance) {
this.importance = importance;
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ID: ");
sb.append(id);
sb.append("\nPAYMENT: ");
sb.append(payment);
sb.append("\nDATE: ");
sb.append(datum);
sb.append("\nUSAGE: ");
sb.append(usage);
sb.append("\nCATEGORY: ");
sb.append(category);
sb.append("\nIMPORTANCE: ");
sb.append(importance);
return sb.toString();
}
}
So, I got also a class for my dates and persons. The question I've got is the following: Should I create for every Table in my database(in Java the Payment.class , Date.class and Person.class) a own transaction/access class which supports an .saveOrUpdate(), .list() or .delete() function?So maybe I got than a PaymentRansaction.class or an PersonTransaction.class.
Thanks for every help :)
It depends.
Do you have one table with transactions, then one model should be sufficient.
Create methods to create the transactions for you depending on Payment or Person.
BUT
If you have more then 1 table go for multiple classess, each table it's own class.
this is my current code to store rooms(it compiles fine) but in the UML there is a variable called addEquipment and there is also another class called Equipment to be defined. I'm having trouble wrapping my head around what I'm supposed to do with this. Am I supposed to create and call an object called Equipment? what goes in addEquipment?
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private String equipmentList;
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public String getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(String anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
}
//Create room object
public Room(int capacity, String equipmentList) {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
return "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
}
}
You can create a new class Equipment and modify your attribute equipmentList to be a List:
public class Equipment {
private String name;
public Equipment(String name) {
this.name = name;
}
}
public class Room {
//begin variable listing
private String name;
private int id;
private int capacity;
private List<Equipment> equipmentList = new ArrayList<Equipment>();
//begins get methods for variables
public String getName(){
return name;
}
public int getID(){
return id;
}
public int getCapacity(){
return capacity;
}
public List<Equipment> getEquipmentList(){
return equipmentList;
}
// Set the variables
public void setName(String aName){
name=aName;
}
public void setID(int anID){
id=anID;
}
public void setCapacity(int aCapacity){
capacity=aCapacity;
}
public void setEquipmentList(List<Equipment> anEquipmentList){
equipmentList=anEquipmentList;
}
public String addEquipment(String newEquipment, String currentEquipment){
Equipment oneEquipment = new Equipment(newEquipment);
equipmentList.add(oneEquipment);
}
//Create room object
public Room() {
setCapacity(capacity);
setEquipmentList(equipmentList);
}
//Convert variables to string version of room
public String toString(){
String capacity=String.valueOf(getCapacity());
String room = "Room "+name+", capacity: "+capacity+", equipment: "+getEquipmentList();
return room;
}
}
In the method addEquipment, you can create a new Equipment and add it to equipmentList, like code above.
An Equipment class could be anything. Lets assume the "Equipment"-class has a String called "name" as it's attribute
public class Equipment {
String name;
public Equipment( String name) {
this.name = name;
}
public String getName() {
return this.name
}
}
When you extend your Room class by the requested "addEquipment" method, you can do something like this.
public class Room {
... // Your code
private int equipmentIndex = 0;
private Equipment[] equipment = new Equipment[10]; // hold 10 Equipment objects
public void addEquipment( Equipment eq ) {
if ( equipmentIndex < 10 ) {
equipment[ equipmentIndex ] = eq;
equipmentIndex++;
System.out.println("Added new equipment: " + eq.getName());
} else {
System.out.println("The equipment " + eq.getName() + " was not added (array is full)");
}
}
}
Now when you call
room.addEquipment( new Equipment("Chair") );
on your previously initialized object of the Room-class, you will get
"Added new equipment: Chair"
Hope this helps a bit.
PS: The code is untestet (maybe there hides a syntax error somewhere)
How to assign value to this function in Java incompatible types?
public class CustomerInfo implements Serializable {
private static final long serialVersionUID = 9083257536541L;
protected String id;
protected String searchkey;
protected String taxid;
protected String name;
protected String postal;
/** Creates a new instance of UserInfoBasic */
public CustomerInfo(String id) {
this.id = id;
this.searchkey = null;
this.taxid = null;
this.name = null;
this.postal = null;
}
public String getId() {
return id;
}
public String getTaxid() {
return taxid;
}
public void setTaxid(String taxid) {
this.taxid = taxid;
}
public String getSearchkey() {
return searchkey;
}
public void setSearchkey(String searchkey) {
this.searchkey = searchkey;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPostal() {
return postal;
}
public void setPostal(String postal) {
this.postal = postal;
}
public String printTaxid() {
return StringUtils.encodeXML(taxid);
}
public String printName() {
return StringUtils.encodeXML(name);
}
#Override
public String toString() {
return getName();
}
}
private CustomerInfo selectedCustomer;
public CustomerInfo getSelectedCustomer() {
// construct a CustomerInfo from the data in your String
return selectedCustomer;
}
private void jcmdOKActionPerformed(java.awt.event.ActionEvent evt) {
selectedCustomer = (CustomerInfo) jListCustomers.getSelectedValue();
//test code
String testing = m_jtxtName.getText();
System.out.println("Now the selectedCustomer is dispayed!");
System.out.println(selectedCustomer);
System.out.println(testing);
//test code
dispose();
}
In the above shown code, I need the string testing value to be assigned to selectedCustomer. How can I assign the value? This is the error I get:
selectedCustomer = m_jtxtName.getText();
incompatible types
required: CustomerInfo
found: String
You can't!!!
selectedCustomer is an object of type CustomerInfo.
m_jtxtName.getText() returns a String
You can't assign a String to a CustomerInfo.
Probably you need to do something like:
int id = 1; //Or whatever new id you have.
String name = m_jtxtName.getText();
selectedCustomer = new CustomerInfo(name); //or whatever id you have.
selectedCustomer.setName(name); //or whatever name you have.
EDIT:
Something is missing from your class. Either it needs setter methods (it has only getters now, so you can't set other properties as name etc) or it needs a constructor with four arguments like:
public CustomerInfo(String id, String searchKey, String taxid, String name, String postal) {
this.id = id;
this.searchKey = searchKey;
// etc
In this case, you might have six jtextfields in your screen, so te user can fill all fields and the create the Customerinfo object by passing all parameters to the constructor.
you cannot do it by simply casting a String to a CustomerInfo object, but you could extend your CustomerInfo but you could try something like this:
public class CustomerInfo {
[...]
public static CustomerInfo createCustomerInfo(String data) {
// construct a CustomerInfo from the data in your String
return createdCustomerInfo;
}
}
I don't know what data you have in that String so i can not give you an advice how to implement this. e.g. If it is the ID you could use this to retrieve the CustomerInfo from database or something like that.