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];
Related
This method I created
public class Use {
private
String firstname;
String lastname;
public String output() {
return "Hii my name is " + firstname + lastname;
}
public String getFirstName() {
return firstname.toUpperCase();
}
public void setFirstName(String jl) {
firstname = jl.strip() ;
}
public String getLastName() {
return lastname.toUpperCase();
}
public void setLastName(String FN) {
lastname = FN.strip();
}
}
And I am trying to use the above method in this code:
import java.util.ArrayList;
import java.util.List;
public class MySweetProgram {
public static void main(String[] args) {
String[] firstnames = {"KARRIK", "KESHAV", "Sussy"};
String[] lastnames = {"gulati", "gulati", "smith"};
List <User> users = new ArrayList<User>();
for (int i = 0; i < firstnames.length; i ++) {
User user = new User();
user.setFirstName(firstnames[i]);
user.setLastName(lastnames[i]);
users.add(user);
}
for (User user : users) {
System.out.println(user.getfullname());
}
}
}
on running getting null null null
1: There is no such class 'Use' in 'MySweetProgram' class (Typo: User)
2: There is no such method in 'Use, class as 'getfullname()'
Solution: Change the class name to User And replace 'getfullname()' with 'output()'.
'
import java.util.ArrayList;
import java.util.List;
public class MySweetProgram {
public static void main(String[] args) {
String[] firstnames = { "KARRIK", "KESHAV", "Sussy" };
String[] lastnames = { "gulati", "gulati", "smith" };
List<User> users = new ArrayList<User>();
for (int i = 0; i < firstnames.length; i++) {
User user = new User();
user.setFirstName(firstnames[i]);
user.setLastName(lastnames[i]);
users.add(user);
}
for (User user : users) {
System.out.println(user.getfullname());
}
}
}
//User Class
class User {
private String firstname;
private String lastname;
public String output() {
return "Hii my name is " + firstname + lastname;
}
public String getfullname() {
return firstname + "_" + lastname;
}
public String getFirstName() {
return firstname.toUpperCase();
}
public void setFirstName(String jl) {
// firstname = jl.strip();// for java 11
firstname = jl;
}
public String getLastName() {
return lastname.toUpperCase();
}
public void setLastName(String FN) {
// lastname = FN.strip();//for java 11
lastname = FN;
}
}
Could someone help me input this data into 3 objects in an ArrayList (one for each player)?
Text file example:
Steve| Barkley| 258| 300
Carl |Johnson |142
Frank|Davidson
Java code:
//couldn't write the normal jfilechoose code above due to space
File playerFile = new File(selectedFile.getAbsolutePath());
Scanner in = new Scanner(playerFile);
String[] playerData; //array to hold data
while (in.hasNext()) {
String data = in.nextLine();
playertData = data.split("\\|");
playerData = Arrays.copyOf(playerData,playerData.length+1);
String firstName = playerData[0];
String lastName = playerData[1];
double playererayear1 = Double.parseDouble(playerData[2]==null?"0":playerData[2]);
double playererayear2 = Double.parseDouble(playerData[3]==null?"0":playerData[3]);
double playererayear3 = Double.parseDouble(playerData[4] == null?"0":playerData[4]);
You can create a separate class for holding information about the Player.
public class Player {
private String firstName;
private String lastName;
private double playerEraYear1;
private double playerEraYear2;
private double playerEraYear3;
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 getPlayerEraYear1() {
return playerEraYear1;
}
public void setPlayerEraYear1(double playerEraYear1) {
this.playerEraYear1 = playerEraYear1;
}
public double getPlayerEraYear2() {
return playerEraYear2;
}
public void setPlayerEraYear2(double playerEraYear2) {
this.playerEraYear2 = playerEraYear2;
}
public double getPlayerEraYear3() {
return playerEraYear3;
}
public void setPlayerEraYear3(double playerEraYear3) {
this.playerEraYear3 = playerEraYear3;
}
}
Now you can parse the file, create a Player object for each of the players and add them to a list
public void parseFile() {
File playerFile = new File(selectedFile.getAbsolutePath());
Scanner in = new Scanner(playerFile);
List<Player> players = new ArrayList<>();
while (in.hasNext()) {
String data = in.nextLine();
String[] playerData = data.split("\\|");
Player p = new Player();
p.setFirstName(playerData[0]);
p.setLastName(playerData[1]);
if (playerData.size >= 3) {
double playererayear1 = Double.parseDouble(playerData[2] == null ? "0" : playerData[2]);
p.setPlayerEraYear1(playererayear1);
}
if (playerData.size >= 4) {
double playererayear2 = Double.parseDouble(playerData[3] == null ? "0" : playerData[3]);
p.setPlayerEraYear2(playererayear2);
}
if (playerData.size >= 5) {
double playererayear3 = Double.parseDouble(playerData[4] == null ? "0" : playerData[4]);
p.setPlayerEraYear3(playererayear3);
}
players.add(p);
}
}
package com.aegle.validator;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Test {
public static void main(String[] args) throws FileNotFoundException {
List<Player> playerList = new ArrayList<Player>();
File playerFile = new File("");//Set your file path
Scanner in = new Scanner(playerFile);
while (in.hasNext()) {
String[] data = in.nextLine().split("\\|");
Player player = new Player(data[0], data[1]);
player.setYears(Arrays.copyOfRange(data, 2, data.length));
playerList.add(player);
}
System.out.println(playerList);//Just to test
}
}
class Player {
String firstName;
String lastName;
String[] years;
public Player(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setYears(String[] years) {
this.years = years;
}
//Introduce getters as you need
#Override
public String toString() {
return "Player{" +
"firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", years=" + Arrays.toString(years) +
'}';
}
}
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;
}
I'm pretty new to programming so I need help. I wanna add the SubjectGrades to the studentList ArrayList. But I think I'm doing the wrong way. What should I do for me to add the SubjectGrades to the ArrayList? Thanks
Here's my partial Main class.
import java.util.Scanner;
import java.util.ArrayList;
public class Main {
private static Scanner in;
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<Student>();
//ArrayList<SubjectGrades> Grades = new ArrayList<SubjectGrades>();
in = new Scanner(System.in);
String search, inSwitch1, inSwitch2;
int inp;
do {
SubjectGrades sGrade = new SubjectGrades();
Student student = new Student();
System.out.println("--------------------------------------");
System.out.println("What do you want to do?");
System.out.println("[1]Add Student");
System.out.println("[2]Find Student");
System.out.println("[3]Exit Program");
System.out.println("--------------------------------------");
inSwitch1 = in.next();
switch (inSwitch1) {
case "1":
System.out.println("Input student's Last Name:");
student.setLastName(in.next());
System.out.println("Input student's First Name:");
student.setFirstName(in.next());
System.out.println("Input student's course:");
student.setCourse(in.next());
System.out.println("Input student's birthday(mm/dd/yyyy)");
student.setBirthday(in.next());
System.out.println("Input Math grade:");
student.subjectGrade.setMathGrade(in.nextDouble());
System.out.println("Input English grade:");
student.subjectGrade.setEnglishGrade(in.nextDouble());
System.out.println("Input Filipino grade:");
student.subjectGrade.setFilipinoGrade(in.nextDouble());
System.out.println("Input Java grade:");
student.subjectGrade.setJavaGrade(in.nextDouble());
System.out.println("Input SoftEng grade:");
student.subjectGrade.setSoftEngGrade(in.nextDouble());
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
break;
//end case 1
Here is my Student Class.
package santiago;
public class Student {
private String lastName;
private String firstName;
private String course;
private String birthday;
SubjectGrades subjectGrade = new SubjectGrades();
public SubjectGrades getSubjectGrade() {
return subjectGrade;
}
public void setSubjectGrade(SubjectGrades subjectGrade) {
this.subjectGrade = subjectGrade;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
}
And my SubjectGrades class
package santiago;
public class SubjectGrades{
Double mathGrade, englishGrade, filipinoGrade, javaGrade, softEngGrade, weightedAverage;
public Double getMathGrade() {
return mathGrade;
}
public void setMathGrade(Double mathGrade) {
this.mathGrade = mathGrade;
}
public Double getEnglishGrade() {
return englishGrade;
}
public void setEnglishGrade(Double englishGrade) {
this.englishGrade = englishGrade;
}
public Double getFilipinoGrade() {
return filipinoGrade;
}
public void setFilipinoGrade(Double filipinoGrade) {
this.filipinoGrade = filipinoGrade;
}
public Double getJavaGrade() {
return javaGrade;
}
public void setJavaGrade(Double javaGrade) {
this.javaGrade = javaGrade;
}
public Double getSoftEngGrade() {
return softEngGrade;
}
public void setSoftEngGrade(Double softEngGrade) {
this.softEngGrade = softEngGrade;
}
public Double getWeightedAverage(){
weightedAverage = ((mathGrade + englishGrade + filipinoGrade + javaGrade + softEngGrade)*3) / 15;
return weightedAverage;
}
public String getScholarStatus(){
String status = "";
if(weightedAverage <= 1.5) {
status = "full-scholar";
} else if (weightedAverage <= 1.75){
status = "half-scholar" ;
} else {
status = "not a scholar";
}
return status;
}
}
Your mistake:
studentList.add(student);
studentList.add(student.setSubjectGrade(sGrade));
You are adding the student, then trying to add a void. The return value of setSubjectGrade is void, so nothing will be added:
Just do:
student.setSubjectGrade(sGrade);
studentList.add(student);
Where sGrade is an Object of type SubjectGrades, which was populated in the same way
student.subjectGrade.setSoftEngGrade(in.nextDouble()); was populated.
Use
ArrayList <SubjectGrades> list;
in student class instead SubjectGrades subjectGrade = new SubjectGrades();.
and generate getters and setters
Just remove this line:
studentList.add(student.setSubjectGrade(sGrade)); //Here it is that I want to add
The way you have done it, the student object already has the subjectGrade attribute with its values set.
You can access it with studentList.get(0).getSubjectGrade()
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
That's the error i get when trying to execute my program. Honestly i really dont know where to start my code.
i have a button name old and new.
i want the textfieldMemberID to display yearToday and an array of members who joined the organization. example if i click new, textfieldMemberId value will automatically display "2012-000001" and if ic lick again new then it will display "2012-000002".
'
i have a Member Class :
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
public class Member {
private ArrayList accounts;
private String MemberId;
private String VotersId;
private String FirstName;
private String MiddleName;
private String LastName;
private String LotNo;
private String Street;
private String Barangay;
private String City;
private String Region;
private int Age;
private String Gender;
private Date Birthday;
private String ContactNo;
private String EmailAddress;
private int size=0;
private int yearToday = Calendar.getInstance().get(Calendar.YEAR);
public Member(String MemberId) {
NumberFormat formatter = new DecimalFormat("000000");
size= this.accounts.size()+1;
this.setMemberId(""+yearToday + "-" + (formatter.format(size)));
} //im trying to have the solution here
public Member(String MemberId,String FirstName,String MiddleName,String LastName){
this.setMemberId(MemberId);
this.setFirstName(FirstName);
this.setMiddleName(MiddleName);
this.setLastName(LastName);
}
public int getAge() {
return Age;
}
public void setAge(int Age) {
this.Age = Age;
}
public String getBarangay() {
return Barangay;
}
public void setBarangay(String Barangay) {
this.Barangay = Barangay;
}
public Date getBirthday() {
return Birthday;
}
public void setBirthday(Date Birthday) {
this.Birthday = Birthday;
}
public String getCity() {
return City;
}
public void setCity(String City) {
this.City = City;
}
public String getContactNo() {
return ContactNo;
}
public void setContactNo(String ContactNo) {
this.ContactNo = ContactNo;
}
public String getEmailAddress() {
return EmailAddress;
}
public void setEmailAddress(String EmailAddress) {
this.EmailAddress = EmailAddress;
}
public String getFirstName() {
return FirstName;
}
public void setFirstName(String FirstName) {
this.FirstName = FirstName;
}
public String getGender() {
return Gender;
}
public void setGender(String Gender) {
this.Gender = Gender;
}
public String getLastName() {
return LastName;
}
public void setLastName(String LastName) {
this.LastName = LastName;
}
public String getLotNo() {
return LotNo;
}
public void setLotNo(String LotNo) {
this.LotNo = LotNo;
}
public String getMemberId() {
return MemberId;
}
public void setMemberId(String MemberId) {
this.MemberId = MemberId;
}
public String getMiddleName() {
return MiddleName;
}
public void setMiddleName(String MiddleName) {
this.MiddleName = MiddleName;
}
public String getRegion() {
return Region;
}
public void setRegion(String Region) {
this.Region = Region;
}
public String getStreet() {
return Street;
}
public void setStreet(String Street) {
this.Street = Street;
}
public String getVotersId() {
return VotersId;
}
public void setVotersId(String VotersId) {
this.VotersId = VotersId;
}
public ArrayList getAccounts() {
return accounts;
}
public void setAccounts(ArrayList accounts) {
this.accounts = accounts;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Member other = (Member) obj;
if ((this.MemberId == null) ? (other.MemberId != null) : !this.MemberId.equals(other.MemberId)) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 5;
hash = 89 * hash + (this.MemberId != null ? this.MemberId.hashCode() : 0);
return hash;
}
#Override
public String toString() {
return "Member{" + "MemberId=" + MemberId + ", VotersId=" + VotersId + ", FirstName=" + FirstName + ", MiddleName=" + MiddleName + ", LastName=" + LastName + ", LotNo=" + LotNo + ", Street=" + Street + ", Barangay=" + Barangay + ", City=" + City + ", Region=" + Region + ", Age=" + Age + ", Gender=" + Gender + ", Birthday=" + Birthday + ", ContactNo=" + ContactNo + ", EmailAddress=" + EmailAddress + '}';
}
}
im trying to call the getmemberId by this code in Button"New"
String last="";
last = member.getMemberId();
this.txtMembersID.setText((last));
but i got this error.
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
pls help. thank u.
The issue occurs on this line of your first constructor:
size= this.accounts.size()+1;
Because accounts has not been initialized yet.
Adding this line before it:
accounts = new ArrayList();
Should fix your problem.
Also, for future reference, one of the most helpful pieces of information you can provide here would be the number of the line causing the exception- makes things a lot easier to solve!