I've been searching for a solution to my problem without any luck. So now I'm asking here for help.
I'm creating "Groups" by the following class:
public class Group {
private String groupID;
private ArrayList<User> usersInGroup;
The User class looks like this:
NOTE: I already have an ArrayList containing all existing Users.
public class User {
private String firstName;
private String lastName;
private String age;
private String gender;
private String usernameID;
private String password;
I'm already adding the groupID field from the "groupData.txt" CSV text file like this:
public static ArrayList<Group> listOfCreatedGroups() throws IOException {
ArrayList<Group> listOfGroups = new ArrayList<>();
FileReader fr = new FileReader("src/groupData.txt");
BufferedReader bfr = new BufferedReader(fr);
String line;
int totalLine = Destination.linesInFile("src/groupData.txt"); //total lines in file
for (int i = 0; i < totalLine; i++) {
line = bfr.readLine();
String[] groupID = line.split(",");
Group temp = new Group();
temp.setGroupID(groupID[0]);
listOfGroups.add(temp);
}
try {
bfr.close();
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
return listOfGroups;
}
The "groupData.txt" file is structured like this:
Line example = groupID,String_1,String2,String3 ... Stringn,\n
groupid,user,user,user,user,user,user,user,
groupid,user,user,user,
groupid,user,user,user,user,user
groupid,user,user
groupid,user,user,user,user
Since I only have the number of users in every group User.usernameID as 1 to n strings in the text file I can't add the whole User object to the Arraylist usersInGroup.
I somehow need to isolate the usernameID's and find the corresponding Users and add them to the ArrayList usersInGroup.
I hope any of you can give me a hint in the right direction. Thanks.
I don't know if this is how you were wanting because I didn't find the user data very specific or even mentioned of how you wanted. But let me know if this is enough
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
public class Group {
private static String groupID;
private static ArrayList<User> usersInGroup = new ArrayList<User>();
public static void main (String [] args) throws IOException {
addListToGroup(readFile());
}
public static void addListToGroup(ArrayList<ArrayList<String>> list) {
for (int i = 0; i < list.size(); i++) {
groupID = list.get(i).get(0);
for (int x = 0; x < list.get(i).size(); x++) {
User temp = new User(); // change this to however you setup the txt file
// the information from the list is in list.get(i).get(x) in order as in the textfile
temp.setAge(null);
temp.setFirstName(null);
temp.setGender(null);
temp.setLastName(null);
temp.setPassword(null);
temp.setUsernameID(null);
usersInGroup.add(temp);
}
}
}
public static ArrayList<ArrayList<String>> readFile() throws IOException {
List<String> temp = new ArrayList<String>();
Path path = Paths.get("file.txt");
temp = Files.readAllLines(path);
ArrayList<ArrayList<String>> lines = new ArrayList<ArrayList<String>>();
for (int i = 0; i < temp.size(); i++) {
String [] s = temp.get(i).split(",");
ArrayList<String> quickArray = new ArrayList<String>();
for (int x=0; x < s.length; x++) {
quickArray.add(s[x]);
}
lines.add(quickArray);
}
return lines;
}
}
class User {
private String firstName;
private String lastName;
private String age;
private String gender;
private String usernameID;
private String password;
//setters and getters
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 getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getUsernameID() {
return usernameID;
}
public void setUsernameID(String usernameID) {
this.usernameID = usernameID;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Related
I have a problem with changing variable value in contact object. I'm trying to make a contact list but I can't change value of variables trought methods. I have editContact method which calls changeName method, both methods are passed ArrayList object trought reference so it shouldn't have problems with changing values trought ArrayList in main method, but problem is when I want to change object's name it won't change it. Is there something I'm missing here?
package telefonski_imenik;
public class Contact {
protected String name;
protected String lastname;
protected String number;
public Contact(String name, String lastname, String number) {
setName(name);
setLastName(lastname);
setNumber(number);
}
public void setName(String name) {
this.name = name;
}
public void setLastName(String lastname) {
this.lastname = lastname;
}
public void setNumber(String number) {
this.number = number;
}
public String getName() {
return this.name;
}
public String getLastName() {
return this.lastname;
}
public String getNumber() {
return this.number;
}
}
package telefonski_imenik;
import java.util.ArrayList;
import java.util.Scanner;
public class TelefonskiImenik {
public static void createContact(String ime, String prezime, String broj, ArrayList<Contact>
ContactList) {
Contact noviKontakt = new Contact(ime, prezime, broj);
ContactList.add(noviKontakt);
}
public static void editContact(ArrayList<Contact> ContactList) {
System.out.println("Unesite nove podatke");
changeName(ContactList);
}
public static void changeName(ArrayList<Contact> ContactList) {
Scanner novinput = new Scanner(System.in);
System.out.println("Unesite staro ime");
String oldName = novinput.nextLine();
System.out.println("Unesite novo ime");
String newName = novinput.nextLine();
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
novinput.close();
}
public static void main(String[] args) {
ArrayList<Contact> ContactList = new ArrayList<Contact>();
Scanner input = new Scanner(System.in);
System.out.println("Unesite podatke");
String name = input.nextLine();
String lastname = input.nextLine();
String number= input.nextLine();
createContact(name, lastname, number, ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
editContact(ContactList);
for (int i = 0; i < ContactList.size(); i++) {
System.out.println(ContactList.get(i).getName());
System.out.println(ContactList.get(i).getLastName());
System.out.println(ContactList.get(i).getNumber());
}
input.close();
}
}
You forgot to get the name of the object in your loop:
for (int i = 0; i < ContactList.size(); i++) {
if (ContactList.get(i).equals(oldName)) {
ContactList.get(i).setName(newName);
}
}
ContactList.get(i).getName().equals(oldName)
I'm trying to read in data from a text file using FileReader. There are four lines of text. Each line has the same attribute types (first name, last name, dob, ssn, etc.). I am trying to split the data read in by the " " delimiter into one long array and then assign the values to a record ArrayList. My logic (if you can even call it that), is that by doing this I'd have one giant array of String data which I could then assign to each of the record's 7 fields - 0-6 for the first record, 7-13 for the second record, 14-20 for the third... But it looks like my while loop is stopping at the end of line one. I feel really stupid here, but I cannot figure out how to get this to work. And yes, I know, there is a lot that is bad form in my code, but I'm just trying to get a feel for the functionality. Any advice here would be most appreciated. Thank you!
The text file looks like this:
John Smith 1996.03.07 123-45-6789 Chickenpox BedRest aspirin
Joe Blow 1996.03.07 123-45-6888 Smallpox BedRest Whiskey
Julie Wilson 1996.03.07 123-45-6999 Insomnia Exercise HotPeppers
Wayne Blaine 1942.07.07 123-45-6777 Measles WaitToGetBetter CodLiverOil
Here's my main.
public static void main(String [] args) throws Exception {
String line = "";
BlockRecord record0 = null;
BlockRecord record1 = null;
BlockRecord record2 = null;
BlockRecord record3 = null;
try {
ArrayList<String> data = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("BlockInput0.txt"));
while((line = reader.readLine()) != null) {
System.out.println(line);
data.add(line);
}
record0 = new BlockRecord();
record1 = new BlockRecord();
record2 = new BlockRecord();
record3 = new BlockRecord();
record0.setBlockID(new String(UUID.randomUUID().toString()));
record1.setBlockID(new String(UUID.randomUUID().toString()));
record2.setBlockID(new String(UUID.randomUUID().toString()));
record3.setBlockID(new String(UUID.randomUUID().toString()));
//manually set until more functionality is in place
data = line.split(" ");
record0.setFirstName(data[0]);
record0.setLastName(data[1]);
record0.setDob(data[2]);
record0.setSsn(data[3]);
record0.setDiagnosis(data[4]);
record0.setTreatment(data[5]);
record0.setRx(data[6]);
record1.setFirstName(data[7]);
record1.setLastName(data[8]);
record1.setDob(data[9]);
record1.setSsn(data[10]);
record1.setDiagnosis(data[11]);
record1.setTreatment(data[12]);
record1.setRx(data[13]);
record2.setFirstName(data[14]);
record2.setLastName(data[15]);
record2.setDob(data[16]);
record2.setSsn(data[17]);
record2.setDiagnosis(data[18]);
record2.setTreatment(data[19]);
record2.setRx(data[20]);
record3.setFirstName(data[21]);
record3.setLastName(data[22]);
record3.setDob(data[23]);
record3.setSsn(data[24]);
record3.setDiagnosis(data[25]);
record3.setTreatment(data[26]);
record3.setRx(data[27]);
}
}catch(Exception e) {
e.printStackTrace();
}
}
Here's my BlockRecord class:
class BlockRecord{
String firstName;
String lastName;
String ssn;
String dob;
String diagnosis;
String treatment;
String rx;
String seed;
String winner;
String blockID;
String previousHash;
String verificationID = "0";
String uuid = UUID.randomUUID().toString();
String winningHash;
public static KeyPair keyPair;
public static int recordCount;
public String getWinningHash() {
return winningHash;
}
public void setWinningHash(String winningHash) {
this.winningHash = winningHash;
}
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 getSsn() {
return ssn;
}
public void setSsn(String ssn) {
this.ssn = ssn;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
public String getTreatment() {
return treatment;
}
public void setTreatment(String treatment) {
this.treatment = treatment;
}
public String getRx() {
return rx;
}
public void setRx(String rx) {
this.rx = rx;
}
public String getSeed() {
return seed;
}
public void setSeed(String seed) {
this.seed = seed;
}
public String getWinner() {
return winner;
}
public void setWinner(String winner) {
this.winner = winner;
}
public String getBlockID() {
return blockID;
}
public void setBlockID(String blockID) {
this.blockID = blockID;
}
public String getPreviousHash() {
return previousHash;
}
public void setPreviousHash(String previousHash) {
this.previousHash = previousHash;
}
public String getVerificationID() {
return verificationID;
}
public void setVerificationID(String verificationID) {
this.verificationID = verificationID;
}
public String getUuid() {
return uuid;
}
public void setUuid(String uuid) {
this.uuid = uuid;
}
}
You read all the lines and add each on them to the list data in the loop:
while((line = reader.readLine()) != null) {
System.out.println(line);
data.add(line);
}
But then, you only split line, which is the last read line.
data = line.split(" ");
Quick fix:
Merge all the lines into one. Then split it.
String mergedLines = "";
while((line = reader.readLine()) != null) {
System.out.println(line);
mergedLines = mergedLines + line;
}
This is really dirty and uneffective as the file already provides separated records.
Better solution:
Create a BlockRecordfor each line without merging them. Then store the record in a list.
ArrayList<BlockRecord> allRecords = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new FileReader("BlockInput0.txt"));
while((line = reader.readLine()) != null) {
System.out.println(line);
data = line.split(" ");
BlockRecord record = new BlockRecord()
record.setFirstName(data[0]);
record.setLastName(data[1]);
record.setDob(data[2]);
record.setSsn(data[3]);
record.setDiagnosis(data[4]);
record.setTreatment(data[5]);
record.setRx(data[6]);
allRecords.add(record)
}
This way, you don't even have to know how many records to declare before reading
I am trying to find the best approach to saving the data I have parsed out of the HTML document when Jsoup into a CSV. The problem I'm having is using [CSVWriter][1] - https://mvnrepository.com/artifact/com.opencsv/opencsv/4.6 and writing the data with it. Please see my code snippet below. The structure of the data looks like the following with infobox being the main listing record with each subsequent field within it. The CSVWriter looks like it is a String Array but having trouble going from elements to write to the CSVData writer with a String Array.
The Jsoup selector is returning an array of items from the selection. For instance, when I make the selection for the name, it is returning all 9 names if there are 9 records on the page. I need to put this data together in order for each row to print into a CSV.
InfoBox >
Name|
Email|
Phone|
Website
The problem I'm having is how I'm trying to write the data on this line below
writer.writeAll((Iterable<String[]>) infoArray);
This is not working correctly and errors but wanted to show what I am kind of after and if there is somebody who's familiar with writing data from Jsoup Elements into CSV. Thanks
String filePath ="c:/results.csv";
// first create file object for file placed at location
// specified by filepath
File file = new File(filePath);
try {
// create FileWriter object with file as parameter
FileWriter outputfile = new FileWriter(file);
// create CSVWriter object filewriter object as parameter
CSVWriter writer = new CSVWriter(outputfile);
String[] header = { "Name", "Phone", "Street","State","City","Zipcode" };
Elements infobox = doc.select(".info");
List<String> infoArray = new ArrayList<>();
for(int i = 0; i < infobox.size(); i++){
infobox.get(i).select(".business-name > span");
infoArray.add(infobox.get(i).select(".business-name > span").text());
infoArray.add(infobox.get(i).select(".phones.phone.primary").text());
infoArray.add(infobox.get(i).select(".street-address").text());
infoArray.add(infobox.get(i).select(".state").text());
infoArray.add(infobox.get(i).select(".city").text());
infoArray.add(infobox.get(i).select(".zip").text());
}
writer.writeNext(header);
//How to write data in order to match each record accordingly?
//Data should be written to CSV like the following example under each header into each corrosponding row
//name, phone, street
writer.writeAll((Iterable<String[]>) infoArray);
for(String ia : infoArray){
}
// closing writer connection
writer.close();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Here's what ended up working for me. The problem was not adding Strings into a String array to pass to CSVWriter. Here is my example.
try {
String[] header = { "Name", "Phone", "Street","State","City","Zipcode" };
Elements infobox = doc.select(".info");
if(count == 0){
writer.writeNext(header);
}
for(int i = 0; i < infobox.size(); i++){
infobox.get(i).select(".business-name > span");
String businessName = infobox.get(i).select(".business-name > span").text();
String phone = infobox.get(i).select(".phones.phone.primary").text();
String address = infobox.get(i).select(".street-address").text();
//Address seems to be displayed another way too
String address2 = infobox.get(i).select(".adr").text();
//Use regular expression to normalize data
String[] columns = new String[]{
businessName, phone, address
};
writer.writeNext(columns);
}
writer.close();
}
Here is little example how to use OpenCSV. Maybe will be helpful for you.
HeaderNames.java
public class HeaderNames
{
public static final String NAME = "Name";
public static final String PHONE = "Phone";
public static final String STREET = "Street";
public static final String STATE = "State";
public static final String CITY = "City";
public static final String ZIPCODE = "Zipcode";
}
DemoDTO.java
import java.io.Serializable;
import com.opencsv.bean.CsvBindByName;
public class DemoDTO implements Serializable
{
private static final long serialVersionUID = 1L;
#CsvBindByName(column = HeaderNames.NAME)
private String name;
#CsvBindByName(column = HeaderNames.PHONE)
private String phone;
#CsvBindByName(column = HeaderNames.STREET)
private String street;
#CsvBindByName(column = HeaderNames.STATE)
private String state;
#CsvBindByName(column = HeaderNames.CITY)
private String city;
#CsvBindByName(column = HeaderNames.ZIPCODE)
private String zipcode;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getPhone()
{
return phone;
}
public void setPhone(String phone)
{
this.phone = phone;
}
public String getStreet()
{
return street;
}
public void setStreet(String street)
{
this.street = street;
}
public String getState()
{
return state;
}
public void setState(String state)
{
this.state = state;
}
public String getCity()
{
return city;
}
public void setCity(String city)
{
this.city = city;
}
public String getZipcode()
{
return zipcode;
}
public void setZipcode(String zipcode)
{
this.zipcode = zipcode;
}
}
Main.java
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import com.opencsv.CSVWriter;
import com.opencsv.bean.HeaderColumnNameMappingStrategy;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import com.opencsv.exceptions.CsvDataTypeMismatchException;
import com.opencsv.exceptions.CsvRequiredFieldEmptyException;
public class Main
{
public static void main(String[] args) throws IOException, CsvDataTypeMismatchException, CsvRequiredFieldEmptyException
{
File file = new File(System.getProperty("user.dir") + System.getProperty("file.separator") + "results.csv");
FileWriter writer = new FileWriter(file);
List<DemoDTO> beans = new ArrayList<DemoDTO>();
for (int i = 0; i < 10; i++)
{
DemoDTO demoDTO = new DemoDTO();
demoDTO.setCity("city " + i);
demoDTO.setName("name " + i);
demoDTO.setPhone("phone " + i);
demoDTO.setState("state " + i);
demoDTO.setStreet("street " + i);
demoDTO.setZipcode("zipcode " + i);
beans.add(demoDTO);
}
HeaderColumnNameMappingStrategy<DemoDTO> strategy = new HeaderColumnNameMappingStrategy<>();
strategy.setType(DemoDTO.class);
StatefulBeanToCsv<DemoDTO> beanToCsv = new StatefulBeanToCsvBuilder<DemoDTO>(writer)
.withSeparator(';')
.withEscapechar(CSVWriter.NO_ESCAPE_CHARACTER)
.withLineEnd(CSVWriter.DEFAULT_LINE_END)
.withQuotechar(CSVWriter.DEFAULT_QUOTE_CHARACTER)
.withMappingStrategy(strategy)
.withThrowExceptions(true)
.build();
beanToCsv.write(beans);
writer.flush();
writer.close();
}
}
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 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];