NullPointerException when adding Object to ArrayList - java

I'm very new to Java and have been trying to set-up an ArrayList CustomerList that takes object Customer, where Customer has attributes from class IAddress. When calling the .add method in my main code however, I am given a NullPointerException error, which I assume is being given because my method isn't receiving anything to add to the ArrayList. I thought it was an issue with the attributes being initialised to empty strings, but when editing them to contain some information, the error still occured.
The ArrayList CustomerList
public class CustomerList {
public ArrayList<Customer> Clients;
public CustomerList() {
Clients = new ArrayList<>();
}
public void add(Customer src) {
Clients.add(src);
}
public void remove(Customer src) {
Clients.remove(src);
}
public void Display(JTextArea jClientsTextArea) {
for (int i = 0; i < Clients.size(); i++) {
Clients.get(i).Display(jClientsTextArea);
}
}
}
Receives Customer from this class
public class Customer {
private String FirstName;
private String Surname;
private IAddress HomeAddress;
public String DOB;
public Customer() {
FirstName = "";
Surname = "";
DOB = "01/01/1900";
HomeAddress = new IAddress();
public void Display(javax.swing.JTextArea jAddressTextArea) {
jAddressTextArea.setLineWrap(true);
jAddressTextArea.append("First Name: " + FirstName + "\n");
jAddressTextArea.append("Surname: " + Surname + "\n");
jAddressTextArea.append("DOB:" + DOB + "\n");
jAddressTextArea.append("Street: " + HomeAddress.getStreet() + "\n");
jAddressTextArea.append("House Name: " + HomeAddress.getHouseName() + "\n");
jAddressTextArea.append("House Number: " + HomeAddress.getHouseNo() + "\n");
jAddressTextArea.append("Area: " + HomeAddress.getArea() + "\n");
jAddressTextArea.append("Postcode: " + HomeAddress.getPostCode() + "\n");
jAddressTextArea.append("Town: " + HomeAddress.getTown() + "\n");
jAddressTextArea.append("Country: " + HomeAddress.getCountry() + "\n");
}
public void Edit(String strfirstname, String strsurname, String strDOB, String strStreet, String strHouseName, String strHouseNo, String strHouseArea, String strPostCode, String strTown, String strCountry) {
FirstName = strfirstname;
Surname = strsurname;
DOB = strDOB;
HomeAddress.setStreet(strStreet);
HomeAddress.setHouseName(strHouseName);
HomeAddress.setHouseNo(strHouseNo);
HomeAddress.setArea(strHouseArea);
HomeAddress.setPostCode(strPostCode);
HomeAddress.setTown(strTown);
HomeAddress.setCountry(strCountry);
}
}
Which receives attributes from IAddress
public class IAddress {
private String Name;
private String Street;
private String HouseNo;
private String HouseName;
private String Area;
private String PostCode;
private String Town;
private String Country;
public IAddress() {
Name = "";
Street = "";
HouseNo = "";
HouseName = "";
Area = "";
PostCode = "";
Town = "";
Country = "";
}
public void setName(String strName) {
Name = strName;
}
public void setStreet(String strStreet) {
Street = strStreet;
}
public void setHouseNo(String strHouseNo) {
HouseNo = strHouseNo;
}
public void setHouseName(String strHouseName) {
HouseName = strHouseName;
}
public void setArea(String strArea) {
Area = strArea;
}
public void setPostCode(String strPostCode) {
PostCode = strPostCode;
}
public void setTown(String strTown) {
Town = strTown;
}
public void setCountry(String strCountry) {
Country = strCountry;
}
}
I've been banging my head against this problem for hours and am ready for it to be something stupidly simple. Thank you.

In your code above the only reason why calling myCustomerList.add(...) could throw is that myCustomerList itself is null. This is because the Clients inside it is initialized in the constructor, and never set to null again. The value of src does not matter as well - the call to Clients.add(src) would succeed even if src is null.
You need to make sure that in your main you do initialize your customer list, like this:
CustomerList list = new CustomerList();

Related

How do I get an array value instead of reference from ObjectMapper in Jackson?

I am trying to get a result from an API response and am able to map everything except for columnHeaders, which is an array of ColumnHeaders. I am instead getting a reference to an array. The code is below.
Response Class
public class Response {
#JsonProperty("searchApiFormatVersion")
private String searchApiFormatVersion;
#JsonProperty("searchName")
private String searchName;
#JsonProperty("description")
private String description;
#JsonProperty("columnHeaders")
private ColumnHeader[] columnHeaders;
public Response(String searchApiFormatVersion, String searchName, String description,
ColumnHeader[] columnHeaders) {
this.searchApiFormatVersion = searchApiFormatVersion;
this.searchName = searchName;
this.description = description;
this.columnHeaders = columnHeaders;
}
public Response(){
}
public String getSearchApiFormatVersion() {
return searchApiFormatVersion;
}
public void setSearchApiFormatVersion(String searchApiFormatVersion) {
this.searchApiFormatVersion = searchApiFormatVersion;
}
public String getSearchName() {
return searchName;
}
public void setSearchName(String searchName) {
this.searchName = searchName;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ColumnHeader[] getColumnHeaders() {
return columnHeaders;
}
public void setColumnHeaders(ColumnHeader[] columnHeaders) {
this.columnHeaders = columnHeaders;
}
#Override
public String toString() {
return "Response{" +
"searchApiFormatVersion='" + searchApiFormatVersion + '\'' +
", searchName='" + searchName + '\'' +
", description='" + description + '\'' +
", totalRowCount=" + totalRowCount +
", returnedRowCount=" + returnedRowCount +
", startingReturnedRowNumber=" + startingReturnedRowNumber +
", basetype='" + basetype + '\'' +
", columnCount=" + columnCount +
", columnHeaders=" + columnHeaders +
'}';
}
}
ColumnHeader class
public class ColumnHeader {
#JsonProperty("text")
private String text;
#JsonProperty("dataType")
private String dataType;
#JsonProperty("hierarchy")
private int hierarchy;
#JsonProperty("parentName")
private String parentName;
#JsonProperty("isEntity")
private Boolean isEntity;
#JsonProperty("isEset")
private Boolean isEset;
public ColumnHeader(String text, String dataType, int hierarchy, String parentName, Boolean isEntity, Boolean isEset) {
this.text = text;
this.dataType = dataType;
this.hierarchy = hierarchy;
this.parentName = parentName;
this.isEntity = isEntity;
this.isEset = isEset;
}
public ColumnHeader(){
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getDataType() {
return dataType;
}
public void setDataType(String dataType) {
this.dataType = dataType;
}
public int getHierarchy() {
return hierarchy;
}
public void setHierarchy(int hierarchy) {
this.hierarchy = hierarchy;
}
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
public Boolean getEntity() {
return isEntity;
}
public void setEntity(Boolean entity) {
isEntity = entity;
}
public Boolean getEset() {
return isEset;
}
public void setEset(Boolean eset) {
isEset = eset;
}
#Override
public String toString() {
return "ColumnHeader{" +
"text='" + text + '\'' +
", dataType='" + dataType + '\'' +
", hierarchy=" + hierarchy +
", parentName='" + parentName + '\'' +
", isEntity=" + isEntity +
", isEset=" + isEset +
'}';
}
}
Service Class
public class BudgetEffortResponseService {
Logger logger = LoggerFactory.getLogger(Response.class);
public Response getResponseFromStringJsonApiResponse(String stringJsonResponse) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper(); //Used to map objects from JSON values specified in Award under #JsonProperty annotation
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
JSONObject stringJsonResponseTurnedIntoJsonObject = new JSONObject(stringJsonResponse);
logger.info("stringJsonResponseTurnedIntoJsonObject: " + stringJsonResponseTurnedIntoJsonObject);
return objectMapper.readValue(stringJsonResponseTurnedIntoJsonObject.toString(), Response.class);
}
}
Main Class
#SpringBootApplication
public class EtlApplication {
public static final String API_USERNAME = System.getenv("API_USERNAME");
public static final String API_PASSWORD = System.getenv("API_PASSWORD");
public static final String API_PREFIX = System.getenv("API_PREFIX");
public static final String API_PATH = System.getenv("API_PATH");
public static void main(String[] args) throws URISyntaxException, JsonProcessingException {
Logger logger = LoggerFactory.getLogger(EtlApplication.class);
logger.info("--------------------Starting process--------------------");
AwardRepository awardRepository = new AwardRepository();
AwardService awardService = new AwardService();
ApiResponseRowService apiResponseRowService = new ApiResponseRowService();
ApiResponseRepository apiResponseRepository = new ApiResponseRepository();
BudgetEffortResponseService budgetEffortResponseService = new BudgetEffortResponseService();
Date startDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 1).getTime();
Date endDateForApiPull = new GregorianCalendar(2023, Calendar.FEBRUARY, 2).getTime();
logger.info("============Starting BudgetEffort API pull from Huron===============");
HttpResponse<String> budgetEffortHttpResponse = apiResponseRepository.getHttpResponseFromApi(startDateForApiPull,
endDateForApiPull, 1, -1, API_PREFIX, API_PATH,
API_USERNAME, API_PASSWORD);
logger.info("BudgetEffortHttpResponse: " + budgetEffortHttpResponse);
logger.info("============End of BudgetEffort API pull from Huron===============");
//Get body of http response string
String budgetEffortResponseString = budgetEffortHttpResponse.body();
logger.info("BudgetEffortResponseString: " + budgetEffortResponseString);
Response budgetEffortResponse = budgetEffortResponseService.getResponseFromStringJsonApiResponse(budgetEffortResponseString);
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
logger.info("--------------------End of process--------------------");
}
}
The response. I'm noticing that I'm getting the reference to the array for columnHeaders and not the values. How would I get the values? Thank you.
BudgetEffortResponse: Response{searchApiFormatVersion='1.0', searchName='Personnel Details for Authorized allocations on Active Awards', description='', columnHeaders=[Lcom.example.etl.entity.budgetEffort.ColumnHeader;#7a7471ce}
The response you get is ok. And also the Array is good. The line
logger.info("BudgetEffortResponse: " + budgetEffortResponse);
uses an indirect cast to String of the Object budgetEffortResponse. In this case all toString() methods of the objects are called. What you need to do in order to print out the Objects is to implement/add the toString() method in the class com.example.etl.entity.budgetEffort.ColumnHeader
Update:
As the toString method is already implemented, the above is partially wrong. But there is a way to use a setting of the ObjectMapper:
ObjectMapper mapper = new ObjectMapper();
// pretty print
String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(budgetEffortResponse);
logger.info("BudgetEffortResponse: " + json);

Having trouble using the compareTo method

Hey all I've recently been trying to learn the compareTo method but this is extremely confusing.
The goal of this program was to hardcode information into a array of objects and sort it by the test score. The problem is compareTo method which I'm having trouble creating since the book I'm using doesn't go in to detail about this method. Here is the code so far.
public class janesj_Lab7 {
public static void main(String[] args) {
CS_UnderGradStudent no1 = new CS_UnderGradStudent(101,"Nancy","Brown","abc#kean.edu",70.0);
CS_UnderGradStudent no2 = new CS_UnderGradStudent(102,"John", "May","def#kean.edu",90);
CS_GradStudent no3 = new CS_GradStudent(103,"William","Smith","xyz#kean.edu",70,"Database");
Object[] arrays = new Object[3];
arrays[0] = no1;
arrays[1] = no2;
arrays[2] = no3;
int x = (int)Student.getGrade();
Arrays.sort(arrays,0,3);
for(int i = 0;i<arrays.length;i++) {
System.out.println(arrays[i].toString());
}
}
public static abstract class Student implements Comparable<Student>{
public static int studentId;
public static String firstName;
public static String lastName;
public static String email;
public static double testScore;
public static String STUDENT_TYPE;
public static double getGrade(){
return testScore;
}
public static String getStudent() {
return STUDENT_TYPE;
}
public Student(int id,String fname, String lname, String email, double testScore){
this.studentId = id;
this.firstName = fname;
this.lastName = lname;
this.email =email;
this.testScore = testScore;
}
#Override
public String toString() {
String x = Double.toString(testScore);
return "\tStudent ID: " + studentId + " name: "+ firstName + ","+ lastName + " Email: " + email + " testScore: " + x;
}
public abstract String computeGrade();
}
public static class CS_UnderGradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE ="CS_UnderGradStudent";
public CS_UnderGradStudent(int id,String fname, String lname, String email, double testScore) {
super(id,fname,lname,email,testScore);
}
public String computeGrade() {
if( testScore>=70) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString(){
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n\t" + "Grade: " + computeGrade();
}
}
public static class CS_GradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE = "CS_GradStudent";
String researchTopic;
public CS_GradStudent(int id,String fname, String lname, String email, double testScore,String r) {
super(id,fname,lname,email,testScore);
researchTopic = r;
}
public String computeGrade() {
if(testScore>= 80) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString() {
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n" + "Grade: " + computeGrade() + "\nResearch Topic: " + researchTopic;
}
}
}
```

Need various ways to come up with this output

I am supposed to come up with this output.
But I am getting this instead..
Here is my code:
import java.lang.*;
import java.util.*;
import java.io.*;
public class Sample{
private String name;
private Hashtable customers = new Hashtable();
private Hashtable movies = new Hashtable();
public Sample(String aName){
name = aName;
}
public String getName(){
return name;
}
public void setName(String aName){
name = aName;
}
public void addCustomer (Customer customer) {
customers.put(customer.getName(), customer);
}
public Customer getCustomer (String customerName) {
return (Customer)customers.get(customerName);
}
public void addMovie (Movie movie) {
movies.put(movie.getName(), movie);
}
public Movie getMovie (String movieName) {
return (Movie)movies.get(movieName);
}
public void error (String message) {
System.out.println ("ERROR: " + message);
}
public Enumeration getMovies() {
return movies.elements();
}
public Enumeration getCustomers() {
return customers.elements();
}
public void showAll() {
System.out.println ("name: "+ this.getName());
Enumeration kk = this.getCustomers();
while (kk.hasMoreElements()) {
Customer one = (Customer) kk.nextElement();
System.out.println (one.show());
}
Enumeration ff = this.getMovies();
while (ff.hasMoreElements()) {
Movie one = (Movie) ff.nextElement();
System.out.println (one.show());
}
}
public void test() {
Customer k1 = new Customer ("Jonah") ; this.addCustomer (k1);
Customer k2 = new Customer ("Hellen") ; this.addCustomer (k2);
Customer k3 = new Customer ("Agnes") ; this.addCustomer (k3) ;
Movie f1 = new Movie ("StarWars"); this.addMovie (f1) ;
Movie f2 = new Movie ("Shrek"); this.addMovie (f2) ;
System.out.println("-**-**- test part 1 -**-**-") ;
this.showAll();
System.out.println("-**-**- test part 2 -**-**-") ;
System.out.println("---" + k1.getName() + " rents " + f1.getName());
this.showAll();
k1.doRent(f1);
MY CUSTOMER CLASS:
package eric;
public class Customer {
String name;
public Customer(String nameCus){
name = nameCus;
}
public String getName(){
return name;
}
public String show(){
return name;
}
public void doRent(Movie f1) {
System.out.println(" -"+ " RentData" + "[" + getName() +"," + f1.getName() + "]" );
}
}
MY MOVIE CLASS:
public class Movie {
String name;
int x = 0;
public Movie(String nameMov){
name = nameMov;
}
public String getName(){
return name;
}
public String show(){
return name+"\n"+" - average: "+x +" days\n"+" - number of rentings: "+x ;
}
}
My problem is that i cannot find a way to fix -RentData [Jonah,StarWars] under the name Jonah... Instead it comes at the end of output.. I need some one to help me figure how am ganna do that.. thanks
You're calling k1.doRent(f1) before this.showAll() so naturally you will get the "RentData..." line printed before the names are printed. The way your code is now is not conducive to what you're trying to do at all. Your Customer class should have a member list called rentedMovies that is populated every time you call doRent(...) on a Customer object. Then, Customer.show() should print the name of the customer, followed by your "RentData..." stuff that comes from rentedMovies.

Java string sorting

This is no homework.Its an exercise I came across in a book.
Build a class named Name which represents the name of a person.The class should have fields that represent first name ,last name ,and fathersname.
The class should have these methods :
public Name (String fn,String f_n,String ln)
/* initializes the fields of an object with the values fn,f_n and m.
fn means first name
ln means last name
f_n means fathersname btw. */
public String getNormalOrder(); //returns the name of the person in the normal order : first name,fathers name,last name.
public String getReverseOrder(); //returns the name of the person in the reverse order : last name,fathers name,first name.
public boolean compare (String fn,String f_n,String ln); // Returns true if the first name is the same with fn,fathers name is the same with f_n, last name with ln.If the opposite happens it returns false.
Build a program named TestName which tests the methods of the class Firstname.
My solution
public class Name {
String fn;
String f_n;
String ln;
public Name(String initialfn, String initialf_n, String initialln) {
fn = initialfn;
f_n = initialf_n;
ln = initialln;
}
public String getNormalOrder() {
return fn + " " + f_n +
" " + ln;
}
public String getReverseOrder() {
return ln + ", " + f_n +
" " + fn + " ";
}
}
How about the third method which is comparing? Also how do I test the class?
For a flexible solution:
public enum NameMember {
FIRSTNAME, SECONDNAME, FATHERSNAME;
}
The Name class:
public class Name {
private final String firstName;
private final String secondName;
private final String fathersName;
public Name(String firstName, String secondName, String fathersName) {
this.firstName = firstName;
this.secondName = secondName;
this.fathersName = fathersName;
}
public String getName(NameMember member1, NameMember member2, NameMember member3) {
StringBuilder sb = new StringBuilder();
return sb.append(getMember(member1)).append(" ")
.append(getMember(member2)).append(" ")
.append(getMember(member3)).toString();
}
public String getMember(NameMember member) {
switch (member) {
case FIRSTNAME:
return firstName;
case SECONDNAME:
return secondName;
case FATHERSNAME:
return fathersName;
default:
return null;
}
}
#Override
public String toString() {
return getName(NameMember.FIRSTNAME, NameMember.SECONDNAME, NameMember.FATHERSNAME);
}
}
A NameComparator (flexible) class:
import java.util.Comparator;
public class NameComparator implements Comparator<Name> {
private NameMember nameMember;
public NameComparator(NameMember nameMember) {
this.nameMember = nameMember;
}
#Override
public int compare(Name name1, Name name2) {
return name1.getMember(nameMember).compareTo(name2.getMember(nameMember));
}
}
And the main class (test drive):
public static void main(String args[]) {
List<Name> names = new ArrayList<>();
names.add(new Name("Alice", "Burda", "Christophe"));
names.add(new Name("Ben", "Ashton", "Caine"));
names.add(new Name("Chane", "Bagwell", "Alex"));
names.add(new Name("Ann", "Clinton", "Brad"));
System.out.println("NAMES ORDERED BY FIRST NAME:");
Collections.sort(names, new NameComparator(NameMember.FIRSTNAME));
printNames(names);
System.out.println("\nNAMES ORDERED BY SECOND NAME:");
Collections.sort(names, new NameComparator(NameMember.SECONDNAME));
printNames(names);
System.out.println("\nNAMES ORDERED BY FATHERSNAME:");
Collections.sort(names, new NameComparator(NameMember.FATHERSNAME));
printNames(names);
}
private static void printNames(Collection<Name> names) {
names.stream().forEach(System.out::println);
}

Enhanced for-loop stopped with NullPointerException

My enhanced for loop doesn't seem to be iterating correctly. The purpose is to use the search class to go through an ArrayList of type Contact and find a specific name but for some reason it only goes through the first contact and stops with an error after that displaying:
Exception in thread "main" java.lang.NullPointerException
at client.AddressBook.search(AddressBook.java:17)
at Main.main(Main.java:31)
My Main class is below:
import client.AddressBook;
import client.Contact;
public class Main {
public static void main(String[] args) {
AddressBook ab = new AddressBook();
Contact c1 = new Contact("jeffm#engr.uconn.edu");
ab.add(c1);
Contact c2 = new Contact("jeffm#engr.uconn.edu", "Jeff Meunier", "jeff");
ab.add(c2);
Contact c3 = new Contact("billgates#engr.uconn.edu", "Bill Gates", "bill");
ab.add(c3);
System.out.println(ab.search("jeff"));
}
}
The AddressBook and Contact class are also listed below:
package client;
import java.util.ArrayList;
public class AddressBook {
ArrayList<Contact> al = new ArrayList<Contact>();
public void add(Contact contactAdd) {
al.add(contactAdd);
}
public Contact search(String searchName) {
for(Contact obj: al) {
if(obj.getNickName().equals(searchName)) {
return obj;
}
}
return null;
}
public String remove(String nickname) {
search(nickname);
al.remove(nickname);
return nickname;
}
public void show() {
int x = 1;
for(Contact obj: al) {
System.out.println(x + ". " + obj.toString());
x++;
}
}
}
package client;
public class Contact {
public String _emailAddress = null;
public String _fullName = null;
public String _nickName = null;
public Contact(String emailaddress, String fullname, String nickname) {
_emailAddress = emailaddress;
_fullName = fullname;
_nickName = nickname;
}
public Contact(String emailaddress) {
_emailAddress = emailaddress;
}
#Override
public String toString() {
if(_fullName == null & _nickName == null) {
//System.out.println("<" + _emailAddress + ">");
return _emailAddress;
}
else {
//System.out.println(_fullName + " (" + _nickName + ") " + "<" + _emailAddress + ">");
return _fullName + " (" + _nickName + ") " + "<" + _emailAddress + ">";
}
}
public String getNickName() {
return _nickName;
}
}
If anyone can give any pointers it would be greatly appreciated. Ultimately right now I am only testing to see whether the search class can search for a specified nickname and then print out the returned value of that. Obviously it should be returning the second Contact (or at least that is the intention).
The problem happen in this validation :
if(obj.getNickName().equals(searchName)) {
return obj;
}
It seems like obj.getNickName() may sometime be null.
Change the order of your validation :
public Contact search(String searchName) {
for(Contact obj: al) {
//I assume that searchName will never be null
if(searchName.equals(obj.getNickName()) {
return obj;
}
}
return null;
}
Your first item you add does not include a nickname. in your search you get the nickname and call equals() on a null reference.

Categories