PriorityQueue java - java

I am writing a priorityqueue class that I want to sort and print based on the account balance. It prints values, but the problem is that it prints the hex values of the parameters passed into the constructor. Where in the code am I going wrong?
Account:
public class Account implements Comparable<Account> {
private String firstName;
private String lastName;
private double balance;
private int accountNumber;
public Account(String firstName, String lastName, double balance, int accountNumber){
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;
this.accountNumber = accountNumber;
}
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 getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public int getAccountNumber() {
return accountNumber;
}
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
public boolean equals(Account x){
return firstName.equals(x.firstName);
}
#Override
public int compareTo(Account o) {
return(int) (this.balance - o.balance);
// Account other = (Account)o;
/*if(balance<other.balance)
return -1;
if(balance==other.balance)
return 0;
return 1;*/
/* int c = this.firstName.compareTo(o.firstName);
if(c < 0){
return -1;
}else if(c == 0){
if(this.balance < 0 && o.balance < 0){
if(this.balance < o.balance){
return 1;
}
}
}
return 1;*/
}
}
AccountApp:
package account;
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.PriorityQueue;
/**
*
* #author saner20
*/
public class AccountApp {
public static void main(String []args){
Account account1 = new Account("billy", "bob", 10.00, 1);
Account account2 = new Account("tom","sawyer", 20.00, 2);
//Account account3 = new Account("bob","builder", 30, 3);
PriorityQueue<Account> account = new PriorityQueue<>();
account.offer(account1);
account.add(account2);
//account.add(account3);
while(!account.isEmpty())
{
System.out.println("Print queue: " + account.remove());
//time.remove();
}
//Arrays.sort(account.toArray());
}
}

Override the toString() method of your Account class.
Something like:
public class Account implements Comparable<Account> {
private String firstName;
private String lastName;
private double balance;
private int accountNumber;
public Account(String firstName, String lastName, double balance, int accountNumber){
this.firstName = firstName;
this.lastName = lastName;
this.balance = balance;
this.accountNumber = accountNumber;
}
// ... other methods
#Override
public String toString() {
return "First name: " + firstName + ", Last name: " + lastName +
", Account number: " + accountNumber + ", Balance: " + balance;
}
}
What you are getting currently is the default implementation of the toString method defined in the Object class, which..
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())

in class Account you should overrite "toString" method. E.g. like that:
#Override
public string toString() {
return "Account{owner=" + firstName + " " + lastName + "; balance=" + balance + "; accountNumber=" + accountNumber + "}";
}
This is auto-called function when you are adding your object to string. E.g
System.out.print(new Account("Josh", "Sad", 10, 10) + " is cool");
You'll get this:
Account{owner=Josh Sad; balance=10; accountNumber=10} is cool

Override the toString()
#Override
public string toString() {
return "Name: " + lastName + ", " + firstName + "\nbalance: " + balance + "\n accountNumber: " + accountNumber;
}

Related

How do I create an boolean equals method compares objects in an array

My programming assignment tasked me with writing an increase/decreasePay abstract method that must be put in my abstract employee class. I can't seem to get the the method correct in HourlyWorker so that it will take increase or decrease the pay by a "percentage". My math is sound (monthly pay - or + (monthly pay * the percentage), but my output in my test class is coming out the same after increasing/decreasing pay. Any help?
Employee class:
abstract public class Employee
{
private String lastName;
private String firstName;
private String ID;
public abstract void increasePay(double percentage);
public abstract void decreasePay(double percentage);
public abstract double getMonthlyPay();
public Employee(String last, String first, String ID)
{
lastName = last;
firstName = first;
this.ID = ID;
}
public void setLast(String last)
{
lastName = last;
}
public void setFirst(String first)
{
firstName = first;
}
public void setIdNumber(String ID)
{
this.ID = ID;
}
public String getLastName()
{
return lastName;
}
public String getFirstName()
{
return firstName;
}
public String getName()
{
return firstName + lastName;
}
public String getIdNumber()
{
return ID;
}
}
HourlyWorkerClass
public class HourlyWorker extends Employee
{
private int hours;
private double hourlyRate;
private double monthlyPay;
public HourlyWorker(String last, String first, String ID, double rate)
{
super(last, first, ID);
hourlyRate = rate;
}
public void setHours(int hours)
{
this.hours = hours;
}
public int getHours()
{
return hours;
}
public void setHourlyRate(double rate)
{
if ( hours > 160 )
this.hourlyRate = hourlyRate * 1.5;
else
this.hourlyRate = rate;
}
public double getHourlyRate()
{
return hourlyRate;
}
public void setMonthlyPay(double monthlyPay)
{
monthlyPay = hourlyRate * hours;
}
public double getMonthlyPay()
{
return hourlyRate * hours;
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + " \nHourly Rate: " + hourlyRate;
return result;
}
}
Testing class (currently testing increase
public class TestEmployee2
{
public static void main(String[] args)
{
Employee [] staff = new Employee[3];
Supervisor sup = new Supervisor("Boss", "Jim", "JB7865", 54000);
HourlyWorker hw1 = new HourlyWorker("Bee", "Busy", "BB1265", 11.95);
hw1.setHours(200);
staff[0] = sup;
staff[1] = hw1;
System.out.println(staff[0].getMonthlyPay());
staff[0].increasePay(5);
System.out.println(staff[0].getMonthlyPay());
System.out.println(staff[1].getMonthlyPay());
staff[1].increasePay(10);
System.out.println(staff[1].getMonthlyPay());
}
}
Supervisor class:
public class Supervisor extends Employee
{
private double annualSalary;
private double monthlyPay;
public Supervisor(String last, String first, String ID, double salary)
{
super(last, first, ID);
annualSalary = salary;
}
public void setAnnualSalary(double salary)
{
annualSalary = salary;
}
public double getAnnualSalary()
{
return annualSalary;
}
public double getMonthlyPay()
{
return ((annualSalary + (annualSalary * .02)) / 12);
}
public void increasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public void decreasePay(double percentage)
{
monthlyPay = monthlyPay* percentage;
}
public String toString()
{
String result = "Name: " + getFirstName() + " " + getLastName() + "\nID: "
+ getIdNumber() + "\nAnnual Salary: " + annualSalary;
return result;
}
}
Output is:
4590.0 4590.0 2390.0 2390.0
Doesn't appear to be modifying getMonthlyPay()
Should be:
4590.00 4819.50 2390.00 2629.00
Generally, when implementing equals(), you compare “key” fields whose values don’t change for the entity, and don’t compare “state” fields whose values change from time to time.
You are comparing sharePrice, when I believe you should be comparing symbol.
When you do list.indexOf(temp), what that does, right now, is look for a Stock that is equals to the argument passed to it -- so it looks for a Stock with price zero, not caring about the symbol at all. That's what the code does right now.
Honestly, using indexOf and equals is not really appropriate for this problem. indexOf is really only useful when you have something that's totally equal to the target you're looking for.
The best way to do something like this is
Optional<Stock> foundStock = list.stream().filter(stock -> stock.getName().equals(symbol)).findAny();
if (foundStock.isPresent()) {
// do something with foundStock.get()
} else {
// no found stock
}
indexOf() is a method return the index of the first occurrence of the specified element in the returned list. If the list does not contain this element, value -1 is returned.
More formally, return the lowest index i that meets the following conditions:
if(o==null? get(i)==null :o.equals(get(i))){
return i;
}
return -1;
If there is no such index, return -1.
And you have override the equals method, I guess you just want to focus on the same price Stock?:
#Override
public boolean equals(Object obj){
if (obj instanceof Stock){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}
return false;
}
As my opinion, you have use List<Stock> list so the Object in the list is all Stock. Maybe it could be simplifed:
#Override
public boolean equals(Object obj){
Stock other = (Stock) obj;
return getPrice() == other.getPrice();
}

Why are my values not being updated and passed correctly?

So, I'm initializing these instances and using the methods in the classes to modify the values. When I print the values within the method modifying them, they print correctly but when they are passed to the "toString" method they print the initial values instead of the modified values.
package com.meritamerica.assignment1;
public class AccountHolder {
/** Bank Account Information */
public String firstName, middleName, lastName, ssn;
public double checkingAccountOpeningBalance, savingsAccountOpeningBalance;
/** Default Constructor */
AccountHolder(){
}
/** Custom Constructor */
AccountHolder
(String firstName,
String middleName,
String lastName,
String ssn,
double checkingAccountOpeningBalance,
double savingsAccountOpeningBalance)
{
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.ssn = ssn;
this.checkingAccountOpeningBalance = checkingAccountOpeningBalance;
this.savingsAccountOpeningBalance = savingsAccountOpeningBalance;
}
/** Getters and Setters */
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getSSN() {
return this.ssn;
}
public void setSSN(String SSN) {
this.ssn = ssn;
}
public CheckingAccount getCheckingAccount() {
CheckingAccount temp = new CheckingAccount(checkingAccountOpeningBalance);
return temp;
}
public SavingsAccount getSavingsAccount() {
SavingsAccount temp = new SavingsAccount(savingsAccountOpeningBalance);
return temp;
}
/** Converts type to String */
#Override
public String toString() {
return "Name: " + this.firstName + " " + this.middleName + " " + this.lastName + "\r\n" +
"SSN: " + ssn + "\r\n" +
"Checking Account Balance: " + this.checkingAccountOpeningBalance + "\r\n" +
"Savings Account Balance " + this.savingsAccountOpeningBalance + "\r\n";
}
}
package com.meritamerica.assignment1;
public class CheckingAccount {
public double openingBalance, interestRate, futureBalance;
CheckingAccount(
double openingBalance)
{
this.openingBalance = openingBalance;
this.interestRate = 0.0001;
}
public double getBalance() {
return this.openingBalance;
}
public double getInterestRate() {
return this.interestRate;
}
public boolean withdraw(double amount) {
if(amount < openingBalance && amount > 0) {
openingBalance -= amount;
return true;
}else {
System.out.println("Not enough money!!!");
return false;
}
}
public boolean deposit(double amount) {
if(amount > 0) {
openingBalance += amount;
return true;
}else {
System.out.println("Cannot deposit a negative amount");
return false;
}
}
public double futureValue(int years) {
futureBalance = (openingBalance * Math.pow(1.0 + interestRate, years));
return futureBalance;
}
#Override
public String toString() {
return "Checking Account Balance: " + getBalance() + "\r\n" +
"Checking Account Interest Rate: " + getInterestRate() + "\r\n" +
"Checking Account Balance in 3 years " + futureValue(3);
}
}
package com.meritamerica.assignment1;
public class SavingsAccount {
public double openingBalance, interestRate, futureBalance;
SavingsAccount(
double openingBalance)
{
this.openingBalance = openingBalance;
this.interestRate = 0.01;
}
public double getBalance() {
return this.openingBalance;
}
public double getInterestRate() {
return this.interestRate;
}
public boolean withdraw(double amount) {
if(amount < openingBalance && amount > 0) {
openingBalance -= amount;
return true;
}else {
System.out.println("Not enough money!!!");
return false;
}
}
public boolean deposit(double amount) {
if(amount > 0) {
openingBalance += amount;
return true;
}else {
System.out.println("Cannot deposit a negative amount");
return false;
}
}
public double futureValue(int years) {
futureBalance = (openingBalance * Math.pow(1.0 + interestRate, years));
return futureBalance;
}
#Override
public String toString() {
return "Checking Account Balance: " + this.openingBalance + "\r\n" +
"Checking Account Interest Rate: " + this.interestRate + "\r\n" +
"Checking Account Balance in 3 years " + this.futureBalance;
}
}
package com.meritamerica.assignment1;
public class MeritAmericaBankApp {
public static void main(String[] args) {
AccountHolder john = new AccountHolder
("John",
"James",
"Doe",
"123-45-6789",
100.0,
1000.0);
System.out.println(john);
john.getCheckingAccount().deposit(500.0);
john.getCheckingAccount().withdraw(800.0);
john.getCheckingAccount().futureValue(3);
System.out.println(john.getCheckingAccount());
System.out.println(john.getSavingsAccount());
You are creating a new CheckingAccount and SavingsAccount objects each time you call getCheckingAccount and getSavingsAccount.
Create a CheckingAccount and SavingsAccount object in the AccountHolder constructor and use it.
CheckingAccount checkingAccount;
SavingsAccount savingsAccount;
AccountHolder (String firstName, String middleName, String lastName, String ssn,
double checkingAccountOpeningBalance,
double savingsAccountOpeningBalance) {
this.firstName = firstName;
this.middleName = middleName;
this.lastName = lastName;
this.ssn = ssn;
this.checkingAccount = new CheckingAccount(checkingAccountOpeningBalance);
this.savingsAccount = new CheckingAccount(savingsAccountOpeningBalance);
}
public CheckingAccount getCheckingAccount() {
return checkingAccount;
}
public SavingsAccount getSavingsAccount() {
return savingsAccount;
}

Any idea why I can not assign a unique number to my SavingsAccount?

I have one abstract class Account and one subclass SavingsAccount, but when I create SavingsAccount object it doesn't assign a number like 1001, 1002, 1003 and so on. Any idea why?
import java.util.ArrayList;
public abstract class Account {
private String accountType;
private static double balance = 0;
private static int accountId;
private static int accountNumberCounter = 1000;
private ArrayList<Account> accounts;
public Account(String acType, int acNumber){
accountType = acType;
accountNumberCounter ++;
accountId = accountNumberCounter;
}
public Account() {
accountNumberCounter++;
accountId = accountNumberCounter;
}
public void addAccounts(Account acc){
accounts.add(acc);
}
public void deposit(double amount){
balance += amount;
}
public abstract boolean withdraw(double value);
public String getAccountInfo(){
return "Account type: " + accountType + ", Account number: " + accountId;
}
public int getAccountNumber(){
return accountId;
}
public String getAccount(){
String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType;
return accountInformation;
}
public void closeCurrentAccount() {
if (balance < 0) {
System.out.println("Your balance: " + balance + "Close your debt");
} else {
System.out.println("Ending balance: " + balance);
}
}
}
And this is SavingsAccount
public class SavingsAccount extends Account {
private static double balance = 0;
private static final double RATE = 1.0;
private static String accountType = "Savings Account";
private static int accountId;
public SavingsAccount(){
super();
}
public double getBalance(){
return balance;
}
public void deposit(double amount){
balance = balance + amount;
}
public boolean withdraw(double amount){
if (balance<= amount){
System.out.println("You have only" + amount + "left on your account.");
return false;
}
else{
balance -= amount;
System.out.println("You put:" + amount);
return true;
}
}
public static String getAccountType(){
return accountType;
}
public static double getRate(){
return RATE;
}
public static double calculateRate(){
return balance += (balance * RATE) / 100;
}
public String getAccount(){
String accountInformation = "Account Number: : " + accountId + "\nAccount Type: " + accountType +
"\nBalance: " + balance + "\nRate: " + RATE;
return accountInformation;
}
}
Maybe it's not needed but here is Customer class as well
import java.util.ArrayList;
public class Customer {
private String name;
private String surname;
private String personalNumber;
private ArrayList<Account> accounts;
public Customer(String customerName, String customerSurname, String customerPersonalNumber)
{
name = customerName;
surname = customerSurname;
personalNumber = customerPersonalNumber;
this.accounts = new ArrayList<Account>();
}
public Customer(){
}
public String getName(){
return name;
}
public String getSurname(){
return surname;
}
public String getPersonalNumber(){
return personalNumber;
}
public void setName(String aName){
name = aName;
}
public void setSurname(String aSurname){
surname = aSurname;
}
public void setPersonalNumber(String aPersonalNumber){
personalNumber = aPersonalNumber;
}
public void addAccounts(Account acc){
accounts.add(acc);
}
public String getCustomerInfo(){
return name + " " + surname + " " + personalNumber;
}
public int getFirstAccountNumber(){
return accounts.get(0).getAccountNumber();
}
public int getLastAccountNumber(){
return accounts.get(accounts.size()-1).getAccountNumber();
}
public ArrayList<Account> getAllAccounts(){
return accounts;
}
}
When I do some tests this unique number doesn't get assigned.
Is it something wrong with a constructor?
You marked accountId as static as well, so every instance of Account will acquire the same id, that is the latest you "generated".
Just mark accountId as a normal instance variable (i.e., remove static).
As a side note, re-declaring accountId in SavingsAccount breaks encapsulation and is, frankly, weird. You inherited getAccountNumber() from Account. Use that instead of accessing accountId directly. You're treating it as a read-only variable anyway.

How can I print the Students info?

Is there a way I can print my students with the information provided?
I created a service class with all the information about the course, where I wish to input my students info on a very simple way.
student class:
public class student {
//Fields
private static String classNumber = "264";
private static String className = "Transfiguration";
private static String instructor = "Professor McGonagall";
private int studentId;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String email;
//Getters and setters
static String getClassNumber(){
return (classNumber);
}
static String getClassName(){
return (className);
}
static String getInstructor(){
return (instructor);
}
static void setClassName(String name){
className = name;
}
int getStudentId(){
return (studentId);
}
String getFirstName(){
return (firstname);
}
String getLastName(){
return (lastname);
}
String getAddress(){
return (address);
}
String getCity(){
return (city);
}
String getState(){
return (state);
}
String getEmail(){
return (email);
}
void setFirstName(String first) {
this.firstname = first;
}
void setLastName(String last) {
this.lastname = last;
}
void setAddress(String rua) {
this.address = rua;
}
void setCity(String cidade) {
this.city = cidade;
}
void setEmail(Sring correio) {
this.email = correio;
}
//Contructors
student(String la) {
this.firstname = first;
this.lastname = last;
this.studentId += 1000;
}
student(String la, int id, String first, String last, String rua, String cidade, String correio) {
this(la);
this.address = rua;
this.city = cidade;
this.email = correio;
}
public String toString() {
String data = "Course: " + classNumber + " " + className +
"\t instructor: " + instructor +
"\t Student Number: " + id +
"\t Student Name: " + firstname + " " + lastname +
"\t Address: " + rua + cidade +
"\t Email: " + correio;
return (data);
}
}
studentTest class:
public class studentTest {
public static void main (String [] args) {
System.out.println("Course: " + student.getClassNumber() + student.getClassName());
student a = new student("Kakashi", "Hatake", "W 69th st", "NY", "khsensei#ninja.com");
student b = new student("Albus", "Dumbledore", "W 116th st", "NY", "princip-al#hogwarts.com" );
student c = new student("Hyuk", "Jang", "321 Maple St", "NJ", "jh#actors.com");
student d = new student("Michael", "Jackson", "543 thriller st", "NY", "mj#singer.com");
student e = new student("Hamilton", "Alexander", "E 86th st", "NY", "justyouwait#broadway.com");
String fname = a.firstname;
System.out.println("First Name: " + fname);
System.out.println(a.toString());
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
}
}
What I wish to do is print all the information on their proper place, however I must have forgotten something pretty serious that I'm getting error messages. Are the students info linked properly to the first class?
--
A few of the error messages I get:
"student.java:114: error: class studentTest is public, should be declared in a file named studentTest.java" - for this one, I've tried before and I can put both classes on the same file, why wouldn't be working now?
Some symbols can't be found:
symbol: variable first
location: class student
student.java:83: error: cannot find symbol
this.lastname = last;
the same also happens with the variables id, last, rua, cidade, and correio.
there's also an error about the constructor
constructor student.student(String) is no applicable
(actual and formal argument lists differ in length)
constructor student.student(String, int, String, String, String, String) is no applicable
student.java:124 error: no suitable constructor found for student (String, String...)
The problem in the code is in this line:
String fname = a.firstname;
You are basically trying to access a private field when you actually want to do is:
String fname = a.getFirstName();
The other problem is the constructor:
student(String la) {
this.firstname = first;
this.lastname = last;
this.studentId += 1000;
}
both first and last variables do not exist in this context.
I've added comments to better point out where the errors are that the compiler is complaining about. These are all very common compiler messages so you should take the time to understand what they are referring to and fix them. You will see them over and over again.
public class student { //class names start with an uppercase letter
//Fields
private static String classNumber = "264";
private static String className = "Transfiguration";
private static String instructor = "Professor McGonagall";
private int studentId;
private String firstname;
private String lastname;
private String address;
private String city;
private String state;
private String email;
//Getters and setters
static String getClassNumber(){
return (classNumber);
}
static String getClassName(){
return (className);
}
static String getInstructor(){
return (instructor);
}
static void setClassName(String name){
className = name;
}
int getStudentId(){
return (studentId);
}
String getFirstName(){
return (firstname);
}
String getLastName(){
return (lastname);
}
String getAddress(){
return (address);
}
String getCity(){
return (city);
}
String getState(){
return (state);
}
String getEmail(){
return (email);
}
void setFirstName(String first) {
this.firstname = first;
}
void setLastName(String last) {
this.lastname = last;
}
void setAddress(String rua) {
this.address = rua;
}
void setCity(String cidade) {
this.city = cidade;
}
void setEmail(Sring correio) { //You misspelled the type of the parameter
this.email = correio;
}
//Contructors
student(String la) {
this.firstname = first; //The parameter list to this constructor
//only contains 'la', 'first' does not exist
this.lastname = last; //The parameter list to this constructor
//only contains 'la', 'last' does not exist
this.studentId += 1000;
}
student(String la, int id, String first, String last, String rua, String cidade, String correio) {
this(la);
this.address = rua;
this.city = cidade;
this.email = correio;
}
public String toString() {
String data = "Course: " + classNumber + " " + className +
"\t instructor: " + instructor +
"\t Student Number: " + id + //id is the parameter in the
//constructor, not the private field name
"\t Student Name: " + firstname + " " + lastname +
"\t Address: " + rua + cidade + //rua and cidade are parameters in the
//constructor, not the private field names
"\t Email: " + correio; //correio is the parameter in the
//constructor, not the private field name
return (data);
}
}
studentTest class:
public class studentTest { //classes start with a capital letter and belong in seprate files
public static void main (String [] args) {
System.out.println("Course: " + student.getClassNumber() + student.getClassName());
//Student's constructor requires 7 arguments of type String, int, String, String, String, String, String
student a = new student("Kakashi", "Hatake", "W 69th st", "NY", "khsensei#ninja.com");
student b = new student("Albus", "Dumbledore", "W 116th st", "NY", "princip-al#hogwarts.com" );
student c = new student("Hyuk", "Jang", "321 Maple St", "NJ", "jh#actors.com");
student d = new student("Michael", "Jackson", "543 thriller st", "NY", "mj#singer.com");
student e = new student("Hamilton", "Alexander", "E 86th st", "NY", "justyouwait#broadway.com");
String fname = a.firstname; //firstname is a private field
System.out.println("First Name: " + fname);
System.out.println(a.toString());
System.out.println(b);
System.out.println(c);
System.out.println(d);
System.out.println(e);
}
}

NullPointerException when Initializing new object

I have a class called CustomerRecord, that another Class, CustomerList contains. When Customer List initializes, everything is fine, but when the first instance of Customer record initializes I get a Null Pointer Exception. Im not sure why this keeps happening but I would much appreciate some help on what is wrong and how to fix it.
Exception in thread "main" java.lang.NullPointerException
at CustomerList.getCustomerList(CustomerList.java:31)
at Assignment3.main(Assignment3.java:16)
Here is my code
public class CustomerRecord {
private int customerNumber;
private String firstName;
private String lastName;
private double balance;
public CustomerRecord() {
super();
}
public int getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber(int customerNumber) {
this.customerNumber = customerNumber;
}
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 getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public String toString(){
return this.customerNumber + " " + this.firstName + " " + this.lastName + " " + this.balance;
}
}
Here is my CustomerList Code
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class CustomerList {
private int count;
private CustomerRecord[] data;
public CustomerList(){
count = 0;
CustomerRecord[] data = new CustomerRecord[100];
}
public void getCustomerList (String fileName){
Scanner fileScan;
try {
fileScan = new Scanner(new File(fileName));
while (fileScan.hasNext()){
if (fileScan.hasNextInt()){
int customerNumber = fileScan.nextInt();
String firstName = fileScan.next();
String lastName = fileScan.next();
double TransactionAmount = fileScan.nextDouble();
data[customerNumber].setBalance(data[customerNumber].getBalance() + TransactionAmount);
}
else{
data[count] = new CustomerRecord();
data[count].setCustomerNumber(count);
data[count].setFirstName(fileScan.next());
data[count].setLastName(fileScan.next());
data[count].setBalance(fileScan.nextDouble());
count++;
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
public CustomerRecord getCustomer (int customerNumber){
if (data[customerNumber] != null){
return data[customerNumber];
}
else
return null;
}
}
When you initialized data in the constructor you weren't actually referring to the same 'data' you had defined. You created a new data and set it to have 100 positions. But you defined it inside the constructor, so it didn't affect your global variable. What you need to do is replace CustomerRecord[] data = new CustomerRecord[100]; for data = new CustomerRecord[100];

Categories

Resources