This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
Since I've finished my code I am debugging every step in the main. I keep hitting a NullPointerException not even 40 lines in. The problem is my setter is not working in my Person class. Or what I assume that my setter isn't working. But I also first believe my read isn't working for my file.
I've tried to change around the variables but I simply can't find the problem and why it won't add the name to the Person class. I read into NullPointerExceptions on here and can't find where that problem is for me to fix in my code.
public class Person {
private String firstName;
private String lastName;
private String address;
private String city;
private String state;
private String zipCode;
public Person(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.state = state;
this.zipCode = zipCode;
}
protected Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
#Override
public String toString() {
return "FirstName: " + firstName + "\nLastName: " + lastName + "\nAddress: " + address + "\nCity: " + city + "\nState: " + state + "\nZipCode: " + zipCode;
}
public String toCSV() {
return this.firstName + "," + this.lastName + "," + this.address + "," + this.city
+ "," + this.state + "," + this.zipCode;
}
public void copy(Person p) {
firstName = p.firstName;
lastName = p.lastName;
address = p.address;
city = p.city;
state = p.state;
zipCode = p.zipCode;
}
public void copy(String firstName, String lastName, String address, String city, String state, String zipCode) {
this.firstName = firstName;
this.lastName = lastName;
this.address = address;
this.city = city;
this.zipCode = zipCode;
}
#Override
public Person clone() {
Person p = new Person(this.firstName, this.lastName, this.address, this.city, this.state, this.zipCode);
return p;
}
}
public class Customer extends Person{
private int customerID;
private double grossSales;
public Customer(int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
this.customerID = customerID;
this.grossSales = grossSales;
}
public Customer(String s, int customerID, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super(firstName, lastName, address, city, state, zipCode);
copyCSV(s);
}
protected Customer() {
}
public int getCustomerID() {
return customerID;
}
public void setCustomerID(int customerID) {
this.customerID = customerID;
}
public double getGrossSales() {
return grossSales;
}
public void setGrossSales(double grossSales) {
this.grossSales = grossSales;
}
#Override
public String toString() {
return "CustomerID: " + customerID + "\nGrossSales: " + grossSales + super.toString();
}
public String toCSV() {
return this.customerID + "," + this.grossSales + "," + super.toCSV();
}
public void copy(Customer c) {
super.copy(c);
customerID = c.customerID;
grossSales = c.grossSales;
}
public void copy(int customerId, double grossSales, String firstName, String lastName, String address, String city, String state, String zipCode) {
super.copy(firstName, lastName, address, city, state, zipCode);
this.customerID = customerId;
this.grossSales = grossSales;
}
public Customer clone() {
Customer c = new Customer(this.customerID, this.grossSales, this.getFirstName(), this.getLastName(), this.getAddress(), this.getCity(), this.getState(), this.getZipCode());
return c;
}
public int compareTo(Customer c) {
int returnValue = 0;
if (this.customerID > c.customerID) {
returnValue = -1;
} else if (this.customerID < c.customerID) {
returnValue = 1;
} else {
returnValue = 0;
}
return returnValue;
}
public void copyCSV(String s) {
List<String> list = new ArrayList<>();
String[] a = s.split(",");
list = Arrays.asList(a);
this.copy(Integer.parseInt(list.get(0)), Double.parseDouble(list.get(1)), list.get(2),
list.get(3), list.get(4), list.get(5), list.get(6), list.get(7));
}
}
public class CustomerList {
public Customer[] cl;
public int size;
public CustomerList() {
this.cl = new Customer[4];
}
public int size() {
return this.size = cl.length;
}
public Customer get(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
return cl[i];
}
public boolean set(Customer c,Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
} else {
cl[i] = c;
return true;
}
}
public void add(Customer c) {
for (int i = 0; i < size; i++) {
if (cl[i] == null) {
cl[i] = c;
} else {
if (i == size) {
Customer[] temp = new Customer[size * 2];
for (int j = 0; j < size; j++) {
temp[j] = cl[j];
}
cl[size] = c;
size++;
}
}
}
}
public Customer remove(Integer i) {
if (i < 0 || i >= size) {
throw new IndexOutOfBoundsException("null");
}
Customer temp = cl[i];
for (int j = 0; j < cl.length - 1; j++) {
cl[i] = cl[i + 1];
}
return temp;
}
#Override
public String toString() {
String s = " ";
double sum = 0;
for(Customer c: cl){
if(c == null)
s = "";
else
s += c + " \n";
}
for(Customer c: cl){
if (c == null)
sum += 0;
else
sum += c.getGrossSales();
}
return s + "\n" + "Total Gross Sales = " + Double.toString(sum);
}
public static CustomerList read(String fn) throws FileNotFoundException {
Scanner input = new Scanner(new File(fn));
CustomerList ab = new CustomerList();
try {
while(input.hasNextLine()) {
String currentline = input.nextLine();
Customer cd = new Customer();
cd.copyCSV(currentline);
cd.toCSV();
ab.add(cd);
}
} finally {
return ab;
}
}
//Write is facing the same problems as read. We can't access the toCSV() method from Customer.
public static boolean write(CustomerList cl, String fn) throws FileNotFoundException {
boolean a = false;
PrintWriter output = new PrintWriter(new File(fn));
// try {
for (int i = 0; i < cl.size; i++) {
Customer cd = new Customer();
cd.toCSV();
// }
// } catch (FileNotFoundException s) {
// System.out.println("File does not exist please try again: ");
// return a;
} return a = true;
}
//I utilized the sort function it said to and assume this will work as expected.
public void sort() {
Arrays.sort(cl);
}
public int indexOf(int id) {
for (int i = 0; i < size; i++) {
if(cl[i].getCustomerID() == id) {
return i;
}
}
return -1;
}
public boolean update(int id, double amt) {
boolean test;
int index = indexOf(id);
if(index == -1) {
System.out.println("CustomerID not present");
test = false;
} else {
amt += cl[index].getGrossSales();
test = true;
}
return test;
}
}
public static void main(String[] args) throws FileNotFoundException {
boolean b = false;
// Read file
System.out.println("Read file");
CustomerList cl = CustomerList.read("Customers.csv");
if(cl != null) {
System.out.println("Read: " + cl.size() + " records");
System.out.println(cl.toString() + "\n\n\n");
} else {
System.out.println("File read error.");
return;
}
// Test get and set for CustomerList
System.out.println("Test get and set for CustomerList");
System.out.println("x = " + cl.get(0));
Customer c = cl.get(0);
c.setFirstName("Homer"); // This is the line it keeps stopping at.
cl.set(c, 0);
System.out.println("x = " + cl.get(0));
System.out.println("\n\n\n");
It should be setting the first name of the customer as "Homer"
The only results it prints out is
Read file
Read: 4 records
Total Gross Sales = 0.0
Test get and set for CustomerList
x = null
--- Exception in thread "main" java.lang.NullPointerException
It's pretty simple, you ask to print cl.get(0). it returns null then you say Customer c = cl.get(0) which is null then you try to do c.setFirstName but c is null so nullPointerException.
Your are trying to access c but c is null. you need to initialize it as a new customer or make it equal to an actual customer (not null) before being able to setFirstName. Just do :
Customer c = new Customer();
c.setFirstName("homer");
It would work if your cl was not empty. To avoid this type of error you could also do :
Customer c;
if (cl.get(0) != null){
c = cl.get(0)
} else {
c = new Customer();
}
c.setFirstName("homer");
Related
Testing an if else statement that does not seem to be working
Assuming it has something to do with possibly changing the IF else to the getter instead of setter?
or something to do with the variable returning an INT instead of string?
little confused been rearranging and modifying this code for a while now and cant get it to work
//package Driver2;
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
r = this.customerPurchase;
if (r > 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private int customerDiscount;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
public int getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Driver1 extends Customer
{
//private int customerPurchase = 0;
//Constructors
/* public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase)
{
super();
this.customerPurchase = customerPurchase;
//this.customerDiscount = customerDiscount;
}*/
public Driver1(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
//super(name, address, number, customerPurchase, customerN, rm);
//this.customerPurchase = customerN;
//this.customerDiscount = pc;
}
public Driver1()
{}
//Accessors
/*
public int getcustomerDiscount()
{
return this.customerDiscount;
}
/*
#Override
public int getcustomerPurchase()
{
return this.customerPurchase;
}
//Mutators
#Override
public void setcustomerPurchase(int c)
{
this.customerPurchase = c;
}*/
/*
public void setcustomerDiscount(int r)
{
this.customerPurchase = r;
if (r >= 500)
{
System.out.print("5%");
}
else if (r >= 1000)
{
System.out.print("6%");
}
else if (r >= 1500)
{
System.out.print("7%");
}
else if (r >= 2000)
{
System.out.print("10%");
}
else
{
System.out.print("");
}
}
*/
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
public class Main
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
System.out.println("Percent off: "+customer.getcustomerDiscount());
}
}
The code you have pasted require some changes actually.Assuming you need to return the discount percentage based on the customer input you need to do the following changes.
1) You have a setCustomerDiscount in Person class but the entity you are dealing here is of Customer type so you need to add the setCustomerDiscount in the Customer class instead of Person class.
2) As you want to show the percentage in String(as per your sysout statements/ you can also change to Int as required) you need to change the return type to String instead of Int.
3) Another thing is your order of the if/else if conditions should be in descending order.
Once you fix them, you can get your output as expected.
Below I have made those changes:
import java.util.Scanner;
class Person{
private String name;
private String address;
private String number;
private int customerPurchase = 0;
//Constructors
public Person(String name, String address, String number, int customerPurchase){
this.name = name;
this.address = address;
this.number = number;
this.customerPurchase = customerPurchase;
}
public Person(){}
//Accessors
public String getName(){
return this.name;
}
public String getAddress(){
return this.address;
}
public String getNumber(){
return this.number;
}
public int getcustomerPurchase(){
return this.customerPurchase;
}
//Mutators
public void setName(String n){
this.name = n;
}
public void setAddress(String a){
this.address = a;
}
public void setNumber(String n){
this.number = n;
}
public void setcustomerPurchase(int a){
this.customerPurchase = a;
}
public void setcustomerDiscount(int r)
{
}
}
///////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////
class Customer extends Person{
private String customerNumber;
private boolean recieveMail;
private String customerDiscount;
//Constructors
public Customer(String name, String address, String number, String customerN, boolean rm, int customerPurchase) {
super(name, address, number, customerPurchase);
this.customerNumber = customerN;
this.recieveMail = rm;
}
public Customer(){}
//Accessors
public String getCustomerNumber(){
return this.customerNumber;
}
public boolean getRecieveMail(){
return this.recieveMail;
}
public String getcustomerDiscount()
{
return customerDiscount;
}
//Mutators
public void setCustomerNumber(String c){
this.customerNumber = c;
}
public void setRecieveMail(boolean r){
this.recieveMail = r;
}
public void setcustomerDiscount(int r)
{
String customerDiscount = "";
if (r >= 2000)
{
customerDiscount="10%";
System.out.print("10%");
}
else if (r >= 1500)
{
customerDiscount="7%";
System.out.print("7%");
}
else if (r >= 1000)
{
customerDiscount="6%";
System.out.print("6%");
}
else if (r > 500)
{
customerDiscount="5%";
System.out.print("5%");
}
else
{
System.out.print("");
}
this.customerDiscount = customerDiscount;
}
}
public class TestMain
{
public static void main(String args[]){
Scanner scanner = new Scanner(System.in);
System.out.print("Enter name of customer:");
String name1 = scanner.nextLine();
System.out.print("Enter address of customer:");
String address1 = scanner.nextLine();
System.out.print("Enter phone number of customer:");
String number1 = scanner.nextLine();
System.out.print("Enter customer number:");
String customerNumber = scanner.nextLine();
System.out.print("Enter yes/no -- does the customer want to recieve mail?:");
String answer = scanner.nextLine();
boolean recieveMail = (answer.equals("yes"));
System.out.print("Enter amount customer has spent:");
int customerPurchase = scanner.nextInt();
scanner.close();
Customer customer = new Customer(name1, address1, number1, customerNumber, recieveMail, customerPurchase);
System.out.println("\nCustomer: ");
System.out.println("Name: "+customer.getName());
System.out.println("Address: "+customer.getAddress());
System.out.println("Phone Number: "+customer.getNumber());
System.out.println("Customer Number: "+customer.getCustomerNumber());
System.out.println("Recieve Mail?: "+customer.getRecieveMail());
System.out.println("Amount Purchased: "+customer.getcustomerPurchase());
customer.setcustomerDiscount(customerPurchase);
System.out.println("Percent off: "+ customer.getcustomerDiscount());
}
}
Hope it helps...
I think it is a logical problem. Simply order the discount formula in reverse.
Catch the big numbers first:
if r >= 2000 print 10%
else if r >= 1500 print 7%
else if r >= 1000 print 6%
else if r >= 500 print 5%
else print nothing
I hope that helps you
Below is the stacktrace of the error:
org.springframework.orm.hibernate3.HibernateSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
Caused by: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:217)
at org.hibernate.util.SerializationHelper.deserialize(SerializationHelper.java:240)
Below is my POJO class :
public static final class MemberName implements java.io.Serializable
{
/**
*
*/
private static final long serialVersionUID = 3832626162173359411L;
private String firstname;
private String lastname;
private String gender;
private String dexterity;
private String matchPreference;
private String tournamentEntry;
/*private Double rating;
private Double minRating=Double.valueOf(2.5);
private Double maxRating=Double.valueOf(5.0);*/
private Integer rating=null;
private Integer minRating=null;
private Integer maxRating=Integer.valueOf(5);
private Integer maxHandicap = Integer.valueOf(100);//Integer.valueOf(6);
private Integer minHandicap = null;
public MemberName() {
}
public String getFirstname() { return this.firstname; }
public void setFirstname(String name) { this.firstname = name; }
public String getLastname() { return this.lastname; }
public void setLastname(String name) { this.lastname = name; }
public Integer getMaxHandicap() { return this.maxHandicap; }
public void setMaxHandcap(Integer d) { this.maxHandicap = d; }
public Integer getMinHandicap() { return this.minHandicap; }
public void setMinHandcap(Integer d) { this.minHandicap = d; }
public String getGender() { return this.gender;}
public void setGender(String gender) {this.gender = gender;}
public String getDexterity() {return this.dexterity;}
public void setDexterity(String dexterity) {this.dexterity = dexterity;}
public String getMatchPreference() {return this.matchPreference;}
public void setMatchPreference(String matchPreference) {this.matchPreference = matchPreference;}
public String getTournamentEntry() {return this.tournamentEntry;}
public void setTournamentEntry(String tournamentEntry) {this.tournamentEntry = tournamentEntry;}
public Integer getRating() {return this.rating;}
public void setRating(Integer r) {this.rating = r;}
public Integer getMinRating() {return this.minRating;}
public void setMinRating(Integer minR) {this.minRating = minR;}
public Integer getMaxRating() {return this.maxRating;}
public void setMaxRating(Integer maxR) {this.maxRating = maxR;}
public boolean isValidSearch()
{
return (null != this.firstname) ||
(null != this.lastname) ||
(null != this.maxRating) ||
(null != this.minRating)||
(null != this.rating)||
(null != this.gender) ||
(null != this.dexterity) ||
(null != this.matchPreference)||
(null != this.tournamentEntry);
}
#Override
public String toString() {
return "MemberName [firstname=" + firstname + ", lastname="
+ lastname + ", gender=" + gender + ", dexterity="
+ dexterity + ", matchPreference=" + matchPreference
+ ", tournamentEntry=" + tournamentEntry + ", rating="
+ rating + ", minRating=" + minRating + ", maxRating="
+ maxRating + "]";
}
}
and I'm using hibernate 3 to fetch the data from User table which is a hibernate pojo class-
public List<User> findUsers(Long cityId, String firstName, String
lastName,
String gender, Double rating, Double minRating, Double maxRating,
String dexterity, String matchPreference, String tournamentEntry) {
StringBuilder sb = new StringBuilder();
if (null != cityId) {
sb.append("u.registeredCity.id=").append(cityId).append(" "); //$NON-NLS-1$ //$NON-NLS-2$
}
if (isNotEmpty(firstName)) {
if (sb.length() > 0) {
sb.append("and "); //$NON-NLS-1$
}
sb.append("u.firstName like '").append(firstName).append("%' ");
}
if (isNotEmpty(lastName)) {
if (sb.length() > 0) {
sb.append("and "); //$NON-NLS-1$
}
sb.append("u.lastName like '").append(lastName).append("%'");
}
sb.append(" order by u.firstName, u.lastName");
if (sb.length() > 0) {
sb.insert(0, "where "); //$NON-NLS-1$
}
sb.insert(0, "from User u "); //$NON-NLS-1$
this.log.info("SQL from findUsers method is::"+sb.toString());
return getHibernateTemplate().find(sb.toString());
}
I've created a Java class called 'Book'. Using this class I'm willing to update information about a new object 'book1'. I'm also wanting to add Author information into the object 'book1'. So, I've dynamically allocated memory using a class-array called 'Author[ ]'. By this I mean there's a separate code in which I've created a class called 'Author' with its own set of instance variables. I'm not getting into that now. However, when I'm testing the class 'Book' using another class called 'TestBook' there's no compilation error BUT I'm getting the following message in the console window when I'm running the code:
Exception in thread "main" java.lang.NullPointerException
at Book.addAuthors(Book.java:34)
at TestBook.main(TestBook.java:12)
The code for 'Book' is shown below:
public class Book {
private String name;
private Author[] A = new Author[];
private int numAuthors = 0;
private double price;
private int qtyInStock;
public Book(String n, Author[] authors, double p) {
name = n;
A = authors;
price = p;
}
public Book(String n, Author[] authors, double p, int qIS) {
name = n;
A = authors;
price = p;
qtyInStock = qIS;
}
public Book(String n, double p, int qIS) {
name = n;
price = p;
qtyInStock = qIS;
}
public String getName() {
return name;
}
/*
public Author getAuthors() {
return A;
}
*/
public void addAuthors(Author newAuthor) {
A[numAuthors] = newAuthor; // THIS LINE IS WHERE THE ERROR POINTS TO
++numAuthors;
}
public void printAuthors() {
/*
for (int i = 0; i < A.length; i++) {
System.out.println(A[i]);
}
*/
for (int i = 0; i < numAuthors; i++) {
System.out.println(A[i]);
}
}
public void setPrice(double p) {
price = p;
}
public double getPrice() {
return price;
}
public void setqtyInStock(int qIS) {
qtyInStock = qIS;
}
public int getqtyInStock() {
return qtyInStock;
}
/*
public String getAuthorName() {
return A.getName();
}
public String getAuthorEmail() {
return A.getEmail();
}
public char getAuthorGender() {
return A.getGender();
}
*/
public String toString() {
/*
return getName() + " " + getAuthor() + " Book price: " + getPrice() +
" Qty left in stock: " + getqtyInStock();
*/
//return getName() + " is written by " + A.length + " authors.";
return getName() + " is written by " + numAuthors + " authors.";
}
}
The code for 'TestBook' is shown below:
public class TestBook {
public static void main(String args[]) {
//Author[] authors = new Author[2];
//authors[0] = new Author("Tapasvi Dumdam Thapashki", "tapasvi#thapashki.com", 'M');
//authors[1] = new Author("Paul Rand", "paulie#aol.com", 'M');
Book book1 = new Book("The Quickie Man", 69.00, 5);
//System.out.println(book1.toString());
//book1.setqtyInStock(5);
//System.out.println(book1.toString());
//System.out.println(book1.getAuthorName() + " " + book1.getAuthorEmail());
//book1.printAuthors();
book1.addAuthors(new Author("Linda Lee", "lindalee#grinchtown.com", 'F'));
book1.addAuthors(new Author("Joseph Caputo", "caputo#lfp.com", 'M'));
System.out.println(book1.toString());
book1.printAuthors();
}
}
The code for 'Author' is shown below:
public class Author {
private String name;
private String email;
private char gender;
public Author(String n, String e, char g) {
name = n;
email = e;
gender = g;
}
public String getName() {
return name;
}
public void setEmail(String e) {
email = e;
}
public String getEmail() {
return email;
}
public char getGender() {
return gender;
}
public String toString() {
return getName() + " [" + getGender() + "] " + getEmail();
}
}
I'd like some help with this.
Initialize Author array with proper size like private Author[] A = new Author[4];
You forgot to specify the size of the Array.
private Author[] A = new Author[15];
For making a dynamic array you can use ArrayList.
private ArrayList<Author> list = new ArrayList<Author>();
addAuthors()
public void addAuthors(Author newAuthor) {
list.add(newAuthor);
}
printAuthors()
public void printAuthors() {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
}
Can someone help solving this. I want to print all the object once please
public class Student {
private static String firstName;
private static String lastName;
private static int studentId;
private static String major;
private static double balance;
public Student (String fName, String lName,int id,String mjr,double blce) {
firstName = new String(fName);
lastName = new String(lName);
studentId = id;
major = new String(mjr);
balance = blce;
}
public String toString () {
return firstName + "\t" + lastName + "\t" + studentId + "\t" + major + "\t$" + balance;
}
public boolean equals (Object obj) {
if (obj instanceof Student) {
Student collegeStud = (Student) obj;
return (this.firstName.equals(collegeStud.firstName));
} else
return false;
}
public static String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public static String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public static int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public static String getMajor() {
return major;
}
public void setMajor(String major) {
this.major = major;
}
public static double getBalance() {
return balance;
}
/*
* .commmm
*/
public void setBalance(double balance) {
this.balance = balance;
}
public static void main (String[] args) {
Student Mike = new Student ("Mike","Versace", 99, "CS",0.00);
Student John = new Student ("John","Sling" ,97, "Maths", 20.00);
Student Bob = new Student ("Bob","Tomson" ,57, "Physic",5.00);
System.out.println (Mike.toString() + "\n" + John.toString());
if (Mike.equals(John))
System.out.println ("Mike is John");
else
System.out.println ("Mike is NOT John");
}
}
import java.io.ObjectInputStream.GetField;
public class StudentList {
private int numberOfStudents=0;
private Student[] studentListArray;
//private int studentCount = 0;
StudentList () {
numberOfStudents=0;
studentListArray = new Student[100];
}
public void createStudent(String firstName, String lastName,int studentId, String major, double balance){
Student collegeStud = new Student(firstName, lastName, studentId, major, balance);
addStudent(collegeStud);
numberOfStudents++;
}
public void addStudent (Student collegeStud) {
studentListArray[numberOfStudents++]=new Student(collegeStud.getFirstName(), collegeStud.getLastName(),
collegeStud.getStudentId(), collegeStud.getMajor(),collegeStud.getBalance());
}
public String toString() {
String result = "";
for (int i=0; i<numberOfStudents; i++) {
result += studentListArray[i].toString() + "\n";
}
return result;
}
public Student[] getList() {
return studentListArray;
}
public int listSize() {
return numberOfStudents;
}
public Student searchForStudent (String firstName){
int index = 0;
while (index < numberOfStudents) {
if (studentListArray[index].equals(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()))) {
return studentListArray[index];
}
index++;
}
return null;
}
public static void main(String args[]) {
StudentList theList = new StudentList();
theList.addStudent (new Student ("John","Sling" ,97, "Maths", 20.00));
theList.addStudent (new Student ("Mike","Versace", 99, "CS",0.00));
theList.addStudent (new Student ("Bob","Tomson" ,57, "Physic",5.00));
//theList.createStudent(new Student(Student.getFirstName(),Student.getLastName(),Student.getStudentId(),Student.getMajor(),Student.getBalance()));
//theList.searchForStudent(new String());
System.out.println (theList.toString());
}
}
The problem is that you marked your fields as static. Remove it and the method will work as expected.
public class Student {
//non-static fields
private String firstName;
private String lastName;
private int studentId;
private String major;
private double balance;
//similar for getters, setters and toString method
}
Static members are shared amongst all objects in a class rather than being one per object. Hence each new object you create is overwriting the data of the previous one.
More info:
What does the 'static' keyword do in a class?
I keep getting a nullPointerException and the rest of my code won't run. I have two classes setup. One is the SalesPerson and the other contains the main method. Line 42 is marked and that is where the nullPointerException occurs.
This is line 42
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
public class SalesPerson {
private String firstName;
private String lastName;
private double firstSales;
private double secondSales;
private double thirdSales;
private double fourthSales;
private double totalSales;
private double salary;
public SalesPerson(String lastName, String firstName, double firstSales,
double secondSales, double thirdSales, double fourthSales,
double totalSales, double salary) {
this.lastName = lastName;
this.firstName = firstName;
this.firstSales = firstSales;
this.secondSales = secondSales;
this.thirdSales = thirdSales;
this.fourthSales = fourthSales;
this.totalSales = totalSales;
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getTotalSales() {
return totalSales;
}
public void setTotalSales(double totalSales) {
this.totalSales = totalSales;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public double getFirstSales() {
return firstSales;
}
public void setFirstSales(double firstSales) {
if (firstSales >= 0) {
this.firstSales = firstSales;
} else {
System.out.println("First sales must be greater than zero.");
}
}
public double getSecondSales() {
return secondSales;
}
public void setSecondSales(double secondSales) {
if (secondSales >= 0) {
this.secondSales = secondSales;
} else {
System.out.println("Second sales must be greater than zero.");
}
}
public double getThirdSales() {
return thirdSales;
}
public void setThirdSales(double thirdSales) {
if (thirdSales >= 0) {
this.thirdSales = thirdSales;
} else {
System.out.println("Third sales must be greater than zero.");
}
}
public double getFourthSales() {
return fourthSales;
}
public void setFourthSales(double fourthSales) {
if (fourthSales >= 0) {
this.fourthSales = fourthSales;
} else {
System.out.println("Fourth sales must be greater than zero.");
}
}
}
SECOND CLASS
import java.io.File;
import java.util.Scanner;
public class Assignment10 {
public static final int NUM_SALESPEOPLE = 20;
public static final double NUM_PER_SALARY = 25;
public static void main(String[] args) {
SalesPerson[] list = new SalesPerson[NUM_SALESPEOPLE];
try {
int people = 0;
Scanner fileInput = new Scanner(new File("A10.txt"));
while (fileInput.hasNext()) {
String lastName = fileInput.next();
String firstName = fileInput.next();
double firstSales = fileInput.nextDouble();
double secondSales = fileInput.nextDouble();
double thirdSales = fileInput.nextDouble();
double fourthSales = fileInput.nextDouble();
double totalSales = firstSales + secondSales + thirdSales + fourthSales;
double salary = NUM_PER_SALARY * totalSales;
SalesPerson person = new SalesPerson(lastName, firstName,
firstSales, secondSales, thirdSales, fourthSales, totalSales, salary);
list[people] = person;
people++;
}
} catch (Exception ex) {
System.out.println("Error opening file.");
}
System.out.println("Full Name Total Sales Salary");
System.out.println("========= =========== ======");
for (int i = 0; i < NUM_SALESPEOPLE; i++) {
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
}
System.out.println("===================================================");
}
}
You are creating an array of size 20. This array will hold only references to NULL. If in your file you have less than 20 entries you will end up with a nullpointerexception.
To be sure, try to print the value of people. If it less than 20 then this is normal.
Your file 'A10.txt' doesn't have 20 (correct) lines.
You should not create an Array. Use ArrayList and Iterator instead and you won't have such problems.
Simply add a check for null:
for (int i = 0; i < NUM_SALESPEOPLE; i++) {
if (list[i] != null) {
System.out.printf("%-20s %15.2f %14.2f %n", list[i].getFirstName() + " " + list[i].getLastName(), list[i].getTotalSales(), list[i].getSalary());
}
}
or declare
int people = 0;
two lines earlier (before your try-block) and use this number of actual read people as the upper bound in your for loop instead of NUM_SALESPEOPLE.