deleting an object from an array [java] - java

My program asks the user to enter the first name, last name and age of 5 people and stores them in an array. I want to write a method that asks the user whom they want to delete from the array and then deletes that employee. I know in arrays you cannot technically delete an object from an array, just replace it.
This is what I've done so far:
private void deleteEmployee(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();
for (int i = 0; i < employees.length; i++) {
if (employees[i].getFirstName().equals(name)){
employees[i] = employees[employees.length - 1];
break;
}
if (i == employees.length - 1) {
System.out.println("That requested person is not employed at this firm.")
}
}
My problem is that it does not decreases the array size by 1, it just replaces the person I want to delete with the last person in my array. My output has the last employee in the array repeated twice (in it's last index and in the index of the person I wanted to delete) How do I fix this?

you can replace the employee with null whenever want to delete it. when inserting a new emplyee, you can first look at a null index and place it.
private void deleteEmployee(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();
for (int i = 0; i < employees.length; i++) {
if (employee[i] != null && employees[i].getFirstName().equals(name)){
employees[i] = null;
break;
}
if (i == employees.length - 1) {
System.out.println("That requested person is not employed at this firm.")
}
}

You may want to use ArrayLists for this problem. ArrayLists are Java's way of creating a mutable array. With arraylists, the array can be automatically expanded and reduced based on the number of objects in the Array.
You can add and delete objects using the index or variable name.
Sample Code:
ArrayList<Employee> employees = new ArrayList<>;
Then you can use the following methods:
employees.remove(int index);
employees.remove(Object o);
Check this out for more reference: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html

One possibility: although you can't change the actual length of the array, you can use another variable to keep track of the "real" length (i.e. the number of elements in the array that you know are valid):
int currentLength = employees.length;
for (int i = 0; i < currentLength; i++) {
if (employees[i].getFirstName().equals(name)){
employees[i] = employees[currentLength - 1];
// employees[currentLength - 1] = null; ... could help reclaim storage
currentLength--;
break;
}
if (i == currentLength - 1) {
System.out.println("That requested person is not employed at this firm.")
}
The program just "knows" that array elements from employees[currentLength] through employees[employees.length - 1] aren't meaningful. You could also set those meaningless elements to null so that there aren't unused references that could prevent some objects from being garbage-collected (this would be important in a larger program). This approach can be a bit error-prone, because you have to remember to use currentLength instead of employees.length. Overall, I think it's better to use an ArrayList, which has a way to delete elements.

The length of an array in Java can not be changed, it's initialized when you create it.
And you can not manual delete a element immediately(like C++). You can set it to null, then wait for the JVM to recycle it.
For convenience, you can use List collection in java.util package. They are convenient for remove/add elements.

I suggest you make use of ArrayList, it already had the remove method. That method also make the size of the list reduce by number of removed items

Hi things will be simpler for you if you use an ArrayList instead of an array, Here is how your code will look like assuming that you have a EmployerClass implementing the getFirstName() method
List<EmployerClass> employees = new ArrayList<EmployerClass>();
// Here is the new type of your employees pool
....
// do whatever you want to put employees in the poll using employees.add(...)
private void deleteEmployee(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name of the employee you want to delete from the list")
String name = scan.nextLine();
EmployerClass tmpEmployer = null;
for(EmployerClass emp : employees) {
if(emp.getFirstName().equals(name)) {
break;
}
}
if(tmpEmployer != null){
// remove the employee to the pool
employees.remove(tmpEmployer);
} else {
System.out.println("That requested person is not employed at this firm.");
}
}
good luck !

You can't really delete it, but you can only make it null.
ArrayList or LinkedList is better for this task. In both you can use builtin methods to add or remove elements and size is handle automatically.

There are some points:
(1) Java array(use the symbol "[]") is a fixed size structure. It means you must specify the size(length) of the array when you create it. Like this:
int[] intArray = new int[10];
The purpose of the specific size is to tell Java compiler to allocate memory. Array is allocated in contiguous memory. Once the allocation has been done, its size could not be changed.(You can image there are other data "behind" the array, if the array is extende, will overlap the other data.)
(2) If you want to get a flexible data collection, for your adding/removing, you can use ArrayList or LinkedList. These Java built-in collections can be extended by themselves if needed.
What's more:
ArrayList is implemented by Java array, it will automatically create a new larger array and copy the data into it when its Capacity is not enough. It has good performance in loop, access elements by index.
LinkedList is implemented by Linked List. It has good performance in insert/remove elements.
For Both lists, if you want to use the remove(Object o) correctly, you have to implement your object's public boolean equals(Object) function.
Ref to the code:
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
public class ListTest {
public static void main(String[] args) {
List<Employee> employees = new LinkedList<Employee>();
// List<Employee> employees = new ArrayList<Employee>();
// Add 3 employees
employees.add(new Employee("Tom", "White", 10));
employees.add(new Employee("Mary", "Black", 20));
employees.add(new Employee("Jack", "Brown", 30));
// See what are in the list
System.out.println(employees);
// Remove the 2nd one.
employees.remove(new Employee("Mary", "Black", 20));
// See what are in the list after removing.
System.out.println(employees);
}
static class Employee {
private String firstName;
private String lastName;
private int age;
public Employee(String firstName, String lastName, int age) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public boolean equals(Object obj) {
if(super.equals(obj)) {
return true;
}
else {
if(obj.getClass() == Employee.class) {
Employee that = (Employee)obj;
return firstName.equals(that.getFirstName()) && lastName.equals(that.getLastName()) && (age == that.getAge());
}
else {
return false;
}
}
}
#Override
public String toString() {
return "Employee [firstName=" + firstName + ", lastName="
+ lastName + ", age=" + age + "]\n";
}
}
}

Related

Can I use public void from a class to make use of it in ArrayList to add age and name?

I'm new to Java and I'm trying to get my head around constructs, classes and objects. I apologise if any of this seems stupid to you.
I have been tasked with creating an ArrayList to hold items of type Data (my class). using the .add method - I should add a certain number of names and ages then output.
I have sort of done it, but I was wondering if I could use the functions like SetAge and SetAge from my class to use within my ArrayList to create a new person and then output it together like I have with the rest. Is there another way?
Thank you for your help & explanation.
Below is my code;
import java.util.ArrayList;
public class workingOn {
public static void main (String[] args)
{
Data Fred = new Data("Fred", 21);
Data Jo = new Data("Jo", 43);
Data Zoe = new Data("Zoe", 37);
ArrayList<Data> myArray = new ArrayList<Data>();
myArray.add(Fred);
myArray.add(Jo);
myArray.add(Zoe);
for (Data temp : myArray)
{
System.out.println(temp.toString());
}
}
}
Below is my class;
public class Data {
private String name;
private int age;
Data(String n,int a)
{
name = n;
age = a;
}
public String GetName()
{
return(name);
}
public void SetName(String n)
{
name = n;
}
public int GetAge()
{
return(age);
}
public void SetAge(int a)
{
age = a;
}
public void Print()
{
System.out.print(("("+ GetName() ));
System.out.print(",");
System.out.print(GetAge());
System.out.print(") ");
}
//i made this so I don't output the object id
public String toString() {
return (name + ", " + age);
}
}
Going through the comments, I am guessing you want to somehow use the setter methods (setName() and setAge()) for the class that you have designed. The easiest way would be:
Data d = new Data("tempName", 10);
myArray.add(d);
This basically creates an object of type Data and adds it to the arraylist. Let's assume that you want to change the name and age of this person you just added, then you should do this:
myArray.get(myArray.size() - 1).setName("newName");
myArray.get(myArray.size() - 1).setAge(18);
To add some explanation, when you add an object to an arraylist, it always adds in the end. We use size() method to get the number of objects in the Arraylist. Since index starts from 0, we use myArray.size() - 1. We use the .get() method to retrieve the object from the arraylist which takes a number as a parameter and return the object at that index.
Combining these two, we get the object at the last possible index, and call the setName() and setAge() function on it.
Hope this helps.

How to specify a class property from a string in java

So I am reading from a file with scanner it has the similar format:
title, name, age
Mr, Matthew, 20
mr, Paul, 30
miss, Anne, 24
CSV^
class person{
String name, title;
int age;
public crimeData(String csv){
String[]list = csv.split(",", -1);
name = list[0];
title = list[1];
age = list[2];
}
}
Console Program
Scanner input = new Scanner(System.in);
System.out.println("Please select what data you want to load:");
String selection = input.next();
int temp = 0;
for(int i=0; i< header.length; i++){
if(header[i].equals(selection)){
temp = i;
break;
}
}
temp will give us the index of the option specified so if it is 2 we will want to access the age property
When my console application runs I prompt them(the user) for the data that they want.
So they may enter "age" So I am lost on how I may take this "age" String and access the person object with it.
The ideal case for the program output should be: 20,30,24 going through each age and printing
I take their input so String input = scanner.nextLine();
Then I loop through my array of person objects to get the index of the input. Once I have this index I then want to access the property of person at the index. So like if my index was 1 I would want to access the property 'name'.
In javascript I could take the string and say person['age'] although java's a whole different story. I have looked into java's "reflection API" although it's a heavy learning curve.
I have looked into java's "reflection API" although it's a heavy learning curve.
Well, Reflection is the way to go. It's widely used in many frameworks.
But perhaps a simpler solution will fit your needs. Use a switch to decide which attribute to return, and encapsulate this in a method of the Person class:
class Person {
private String name, title;
private int age;
public loadData(String csv){
String[] list = csv.split(",");
name = list[0];
title = list[1];
age = Integer.parseInt(list[2]);
}
public Object attribute(String attribute) {
switch (attribute) {
case "name": return this.name;
case "title": return this.title;
case "age": return this.age;
default: throw new RuntimeException("Invalid attribute: " + attribute);
}
}
}
Encapsulating the switch inside the method is in line with OOP principles, since it hides how attributes are stored from other objects, only exposing an interface to query them. Reflection breaks all encapsulation.
Though in general I am not in favor of using Map for holding fields for an object, if the number of properties is large and could even potentially vary across CSV files (e.g., some file has the University a person attended, another does not), then using a Map to hold the properties might be appropriate.
In this case, one would define a simple Person class:
public class Person {
Map<String, String> props = new HashMap<>();
public void addProperty(String propertyName, String value) {
// could add error checking to ensure propertyName not null/emtpy
props.put(propertyName, value);
}
/**
* returns the value of the property; may return null
*/
public String getProperty(String propertyName) {
return props.get(propertyName);
}
}
If it is know that certain attributes/properties will always be loaded, then accessors such as getName() could be added:
public String getName() {
return props.get("name");
}
public int getAge() {
String age = props.get("age");
// or throw exception if missing
return (age != null ? Integer.parseInt(age) : -1);
}
Though note I would expect name to not be a single entry for most datasets, as there typically would be last name, first name, etc. Nonetheless, the pattern for a limited number of commonly expected values is the same. Also, you can adapt so that you could get integer values directly for certain well-known fields.
Then, when you parse the file, you keep the title row that has the attribute definitions. Then for each row that you subsequently read, you create a new Person object, and then add the properties in order.
List<Person> allPersons = new ArrayList<>();
while ( (line = READ_NEXT_LINE) ) {
// NOTE: this is not a safe way to handle CSV files; should really
// use a CSV reader as fields could have embedded commas
attrs[] = line.split(",");
Person p = new Person();
for (int i = 0; i < titleRow.length; ++i) {
p.addProperty(titleRow[i], attrs[i]);
}
allPersons.add(p);
}
You can then get a specific Person by Person myPerson = allPersons.get(index_of_person), and much akin to the way you would have used Javascript, you can do String val = myPerson.getProperty("age").
If you need to search by a given attribute, you can then stream/loop over the allPersons and check of equivalence based upon a given property.
// find all people of a given age
List<Person> peopleAge20 = allPersons.stream()
.filter(p -> p.getAge() == 20)
.collect(Collectors.toList());
System.out.println(peopleAge20);
// summary statics (average age) for all people
IntSummaryStatistics stats =
allPersons.stream().mapToInt(p -> p.getAge()).summaryStatistics();
System.out.printf("Average age: %f\n", stats.getAverage());
Note that this approach does break the idea of a Javabean, but that may or may not be an issue depending upon your requirements.
First thing, we should add a constructor to your Person class.
class Person {
public Person(String name, String title, int age) {
this.name = name;
this.title = title;
this.age = age;
}
}
Now while you read the input you can use a Map as follows. Here after reading each line, we create a Person object and then using that person's age we make an entry in the map with key as age and value as Person.
Map<Integer, Person> mapOfPeople = new HashMap<>();
while (input.hasNextLine()) {
String line[] = input.nextLine().split(",");
Perso person = new Perso(line[1], line[0], Integer.parseInt(line[2].trim()));
mapOfPeople.put(person.getAge(), person);
}
Now to fetch a particular Person by age just do
mapOfPeople.get(20);

how do i add or delete something from an array?

I am writing this program that will take in the names, ages and salaries for 5 different people from the user and will put them in an array.
I then want to write a method that will ask the user for another name, age and salary and add that into the array. Also a method that will as for the name of someone who's already in the array and will delete the information of the person with that age from the array.
The first method will increase the array size by 1 and the second will decrease the array size by 1. so far this is what I have:
ArrayList<details> details = new ArrayList<details>();
for(int x = 0; x < 4; x++) {
Scanner scan = new Scanner(System.in);
System.out.println("Enter the first name: ");
String firstName = scan.nextLine();
System.out.println("Enter the last name: ");
String lastName = scan.nextLine();
System.out.println("Enter the age: ");
int age = scan.nextInt();
System.out.println("Enter the salary: ");
double salary = scan.nextDouble();
details.add (new details(firstName, lastName, age, salary));
}
I don't know how to go about doing this. I need some help!
thanks!
You can have a class Person with the class variables you require (name,age,salary)
class Person {
private int age;
private dobule salary;
private String firstname;
private String lastname;
}
Define the getter and setter methods for each of the class variables. For e.g
public void setAge(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
In your main class read the input from STDIN as you are doing it. Instantiate the Person object for each of the 5 person.
Person employee = new Person();
employee.setAge(x);
employee.setFirstName(x);
employee.setLastName(y);
employee.setSalary(y);
Now, you can add each Person to your list and remove them too.
For removing any Person you would have to search for the Person through the ArrayList by name. That would be iterating over the length of ArrayList and comparing the name of each.
The final class would look like,
public class Solution{
private ArrayList<Person> details = new ArrayList()<Person>;
public static void main(){
// Here you loop for reading from STDIN as you are already doing.
// addPerson() would be used to add to ArrayList and removePerson() for the other
}
public addPerson(String firstName, String lastName, int age, int salary){
//Create the Person object
details.add(<person object>);
}
public removePerson(name){
details.remove(index);
// to get index it would require iterating over the ArrayList.
// It would be better if you use a Map instead (as other suggest)
// with name as the key
}
}
Hope this helps.
dud first of all, i can see that u have used arrayList name & Class name both same so please update that.
secondary use Map in place of Class like in if condition
if(){
Map userDetails = new HashMap();
map.put("firstname",firstname);
..
..
map.put("salary",scan.nextDouble());
details.add(map)
}
and on time of delete iterate ArrayList
for(int i=0;i<details.size();i++){
Map tempMap = details.get(i);
if(temp.get("firstname").toString() == "Given Name"){
}else{
// your logic
}
}
Hope will help you please let me know if any doubts.
use this code for removing employee
void removeEmployee(String name){
for(Employee emp :details){
if(name.equals(emp.getName())){
details.remove(emp);
break;
}
}
}
and do include exception handling

How to load an ArrayList with instances of an Object I created

NOTE: I edited my code to how I think people are trying to tell me but it still doesn't give me my desired output. Now my output is "examples.search.Person#55acc1c2" however many times I enter new first and last names. At least it's making it through the code with out crashing lol
I am learning how to use ArrayLists and need to load an Array list with instances of an Object I created. I know how to do this with an array but for this assignment I need to do it with an ArrayList. Here's an example of what I need to do.
// my "main" class
package examples.search;
import java.util.ArrayList;
import dmit104.Util;
public class MyPeople {
public static void main(String[] args) {
ArrayList<Person> people = new ArrayList<Person>();
Person tempPerson = new Person();
String firstName;
String lastName;
char choice = 'y';
int count = 1;
// fill my ArrayList
do {
people.add(tempPerson);
// I have a Util class that has a prompt method in it
firstName = Util.prompt("Enter First Name: ");
lastName = Util.prompt("Enter Last Name: ");
tempPerson.setFirstName(firstName);
tempPerson.setLastName(lastName);
count++;
choice = Util.prompt(
"Enter another person? [y or n]: ")
.toLowerCase().charAt(0);
} while (choice == 'y');
// display my list of people
for(int i = 0; i < people.size(); i += 1) {
System.out.print(people.get(i));
}
}
}
// my Person class which I am trying to build from
public class Person {
// instance variables
private String firstName;
private String lastName;
// default constructor
public 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;
}
}
I've tried it a number of ways but no matter what my ArrayList doesn't fill up. Like I mentioned I can do it no problem with an array or even if I had a loaded constructor method but I don't. In my actual assignment I am supposed to do it with the set methods.
I have looked everywhere and cannot find the solution for my problem and being friday my instructor isn't in.
Thank you so much in advance
Leo
You'll have to create a Person and then add it to the ArrayList.
for (int i = 0; i < count; i++) {
Person person = new Person();
person.setFirstName("Foo");
person.setLastName("Bar");
people.add(person);
}
Its crashing because your line people.get(i).setFirstName(firstName); is first trying to what is at index i, but you have not set anything yet.
Either first set people[i] to a empty Person, or make a person using firstName and lastName, and add it to people using people.add(person);
You have an ArrayList<Person>, but that alone only defines a list of potential Person instances. But so far, each of the list entries is null. The get(i) returns null, and the following null.setFirstName(..) causes a NullPointerException.
So you need to create the instances of Person that are supposed to go into the list:
firstName = Util.prompt("Enter First Name: ");
Person p = new Person(); //create the instance
people.add(p); //add the instance to the list
p.setFirstName("..."); //set any values
Now you are storing the Person Object into an ArrayList and printing that Object.
To print the firstname and lastName when you print the Person object, you will have to override toString method.
Add the following code in your Person class
public String toString(){
return String.format("[Personn: firstName:%s ,lastName: %s]", firstName,lastName);
}
As for the second question you had, you have to override the toString() method in the Person class. The outputs you are getting, such as examples.search.Person#55acc1c2 is the default toString() method from the Object class, which is defined as class#hashCode

Java Input Output Logic

First of all, id like to thank this fourm, as I am finding myself quickly improving through all the material on this forum and all the help different members have been giving me. So this is just a big thank you for all of that. As for my question, I've been experimenting around with input out and wanted to see if this logic would work. I am trying to get the appropriate things in their appropriate array, and wanted to see if this logic would do it. Currently (and for a while) I wont be in a place where I can access any Virtual IDE effectively so all this was kinda done on the fly using notepad, word etc. *So don't be to hard on my syntax. What I am mostly concerned about is the logic (if it would work) and to a lesser mistake any major mistakes in code.*
Thanks alot.
So basically, the text file goes like this. Title, one line of space, then name, age and wage and the separator is the #. Then right below that, name, age and wage the separator bring # etc etc.
(pretend there was no line spaces between Bobby, Sandy, Roger, Eric and David..so pretend in the txt file they are right under each other, but there is a gap in between information and bobby.
Information
Bobby#24#5.75
Sandy #19#10.22
Roger #27#6.73
Eric#31#8.99
David#12#3.50**
Here is the logic i've come up with.
public class Practice {
public static void main(String[] args) throws Exception {
String Name [] = new String [5];
int Age [] = new int [5] ;
double Wage [] = new double [5];
String Blank [] = new String [5];
FileReader inputfile = new FileReader (new File(info.txt));
BufferedReader InputBuffer = new BufferedReader (inputfile);
String Title = InputBuffer.readline (); // to get the title
int count = 0;
while (InputBuffer.readline() = null) { // this while loop grabs the blank under the title
Blank [count] = count;
}
int i = 0;
while (InputBuffer.readline() !=null) {
String Getter = InputBuffer.readline (); // reads line
String splitup= Getter.split(#); // splits it
Name [i] = splitup[i]; // puts name in this array
Age [i] = splitup([i] + 1); // age in this array
Wage [i] = splitup([i] + 2); // wage in this array
}
InputBuffer.close();
}
}
Would this logic work for storing the title in the title String, the Blank line under the Blank Array, the name under the name array, age under the age array and the wage under the wage array??
Thanks alot.
P.S: Mostly concerned about the last while loop, I want to know if it will put the name in the name array, the age in the age array and the wage in the wage array.
First of all, you only need one while-loop. I don't understand why you have two, especially since the conditional in the first is nonsensical ( InputBuffer.readline() = null ).
Your loop would look something like this:
boolean isTitleParsed = false;
String title;
String line;
while ( (line = inputBuffer.readLine()) != null ) {
if (!isTitleParsed) {
// this is the title
title = line;
isTitleParsed = true;
} else if (line.isEmpty()) {
// this is a blank line; logic for dealing with blank lines here
...
} else {
// this is actual person data
String[] personData = line.split("#");
if (personData != null && personData.length == 3) {
String name = personData[0];
String age = personData[1];
String wage = personData[2];
...
}
...
}
}
Secondly, I think using arrays is entirely the wrong way to go. Like #AVD mentioned in his comment on the OP, List<T> and a POJO is probably a much better solution -- and much more extensible.
And finally: no, as you've written it, your second loop will not successfully save the name, age, and wage to the arrays. You never increment i and the syntax splitup([i] + 1) is just wrong. (You probably meant splitup[i+1].)
Using Arrays
If you're really stuck on using arrays to save your data, you'd have to do in something like this:
String[] names = new String[5];
String[] ages = new String[5];
String[] wages = new String[5];
...
int index = 0;
while ( (line = inputBuffer.readLine()) != null && index < 5) {
if (!isTitleParsed) {
...
} else if (line.isEmpty()) {
...
} else {
// this is actual person data
String[] personData = line.split("#");
if (personData != null && personData.length == 3) {
String name = personData[0];
String age = personData[1];
String wage = personData[2];
names[index] = name;
ages[index] = age;
wages[index] = wage;
index++;
} else {
System.err.println("Line " + line + " is malformed and was not saved.");
}
...
}
}
Notice that index is instantiated at 0, but is incremented every time we save something to the arrays. This way names[0] will hold the first name, names[1] will hold the second, and so on.
Notice also that we save a given record's name, age, and wage all at the same index. So we could expect names[0] to hold "Bobby", ages[0] to hold "24", and wages[0] to hold "5.75" -- all of which are related to the same record.
Finally, the condition in the while loop has been amended to be (line = inputBuffer.readLine()) != null && index < 5. This means we'll keep looping through the lines of the file until we either run out of lines (the file ends) or our index becomes greater than 5, which is the size at which we instantiated the array. This is one reason why arrays are such a bad structure to hold this data: you have to know exactly how many records you have in your file, and you may end up not filling them all the way (you allocated too much space) or not saving some records because you have no more room to store them.
Using POJOs
A much better way to save the data would be to use a POJO -- a Plain Old Java Object. This kind of object is pretty much a "data holder" object.
In your case, it would be something like this:
public class PersonData {
private String name;
private String wage;
private String age;
public PersonData() {
this(null, null, null);
}
public PersonData(String name, String wage, String age) {
this.name = name;
this.wage = wage;
this.age = age;
}
// ... getters and setters here
}
In your code, you'd replace your arrays with a List structure of PersonData objects:
List<PersonData> records = new ArrayList<PersonData>();
And in your while loop, you'd save into these objects instead of into the arrays:
// in the else in the while loop:
String[] data = line.split("#");
if (data != null && data.length == 3) {
PersonData record = new PersonData(data[0], data[1], data[2]);
records.add(record);
} else {
// error handling for malformed line
}
Now if you wanted to get data for a particular record, you'd just need to extract the PersonData object from your records list and query it:
// assuming the first record we scraped was "Bobby#24#5.75"
PersonData person = records.get(0);
person.getName(); // returns "Bobby"
person.getAge(); // returns 24
person.getWage(); // returns 5.75
Since we're using a List and not an array, we don't have to worry about knowing exactly how many records there are in the file, and we don't run the risk of losing information because we don't have anywhere to store it.
This way we can also know for certain that a name, age, and wage are all related to the same record, whereas before we were just hoping that, say, all records at index 0 in the arrays were related to the same person.
Also, if you add additional data to the records -- for example, name#age#wage#favorite food -- all you have to do is add a new field to the PersonData object and add a line in your parsing method to add that data to the object. If you were using arrays, you'd need to add a new array, and so on.
It's also much easier to create logic if, say, you have a row that only has a name or that missing a wage, and so on -- so that you're actually able to save the data in some meaningful fashion.
If you want to make good progress in Java or any OOP Language for that matter you should always approach a problem in a Object Oriented Manner.
For the problem at hand you should always consider a class to store the Person Info rather than using associative arrays.
class PersonInfo {
PersonInfo(String name,int age,float wage) {
this.name = name;
this.age = age;
this.wage = wage;
}
String name;
int age;
float wage;
}
The code is more or less the same from above...but it should give a List of PeopleInfo as output.
List<PersonInfo> peopleInfo = new ArrayList<String>();
boolean isTitleParsed = false;
while ( (line = inputBuffer.readLine()) != null ) {
if (!isTitleParsed) {
// this is the title
title = line;
isTitleParsed = true;
continue;
} else if (line.isEmpty()) {
// this is a blank line; logic for dealing with blank lines here
} else {
String[] personData = line.split("#");
if (personData != null && personData.length == 3) {
peopleInfo.add(new PersonInfo(personData[0],personData[1],personData[2]));
}
}

Categories