To add an element to arraylist [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
public class Person {
private String name;
private boolean adopted;
private String parent;
private List<String> children;
public Person(String Aname) {
name = Aname;
children = new ArrayList<String>();
adopted = false;
}
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(name)
&& children.size() <= 10) {
person.parent = name;
// System.out.println(parent);
// children=person.name;
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
// System.out.println(children);
adopted = true;
}
}
public void setName(String name) {
this.name = name;
}
public void disown(Person person) {
}
public String toString() {
if (children.size() == 0 && parent == null) {
return name + " Parent: No parent. Children: No children ";
} else if (children.size() == 0) {
return name + " Parent: " + parent + " Children: No children";
} else if (parent == null) {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: No Parent " + "Children: " + list;
} else {
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
}
}
}
In this I am trying to add person.name to arraylist children but I am not able to add. I am initialyzing the list then adding a name to the list.I am using adopt method to add children to the list. Please tell what am I doing wrong here.

The properties are private, please put setters and getters and then try to access to the getName() property.

The following code is incorrect:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
Each time you call Adopt(person) you add that child instead of all the children in the list.
Try using:
children.add(person.name);
EDIT:
Ok, the above is correct, but cristobal de Leon's answer is the explanation to what you're experiencing.

I'm pretty sure the problem is that after you create the new ArrayList(); you never assign any value to the list, so when you iterate based on children.size(), you will always iterate from 0 to 0 and never add any children in the next snippet:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
As per #summerbulb suggestion: person.name should be adopted by the current this so you should just do
children.add(person.name)
Also, at the end of the adopt method, I think you want to mark person (the parameter) as adopted and not this (the person adopting), so you may change
person.adopted=true;
instead of just adopted=true;

The number of items in you arraylist "children" is 0.
Look at this part code:
for (int i = 0; i < children.size(); i++) {
children.add(i, person.name);
}
for every object in children you will set the same name.
So you will set the name 0 times. That means there also won't be any output.
I think you need an array with al the persons you create in you main.
Change the adopt code to this:
public void adopt(Person person) {
if (!person.adopted && !person.name.equals(this.name)) {
person.parent = name;
children.add(person.name);
person.adopted = true;
}
}
Make getters for your atributes or make them public like this:
public String name;
In your main:
Person[] persons = new Person[5];
persons[0] = new Person("Dude");
persons[1] = new Person("Dude's child");
persons[0].adopt(persons[1]);

Check your toString method. I am not sure if all children are printed. E.g. look at the case in which parent is not NULL and children.size() > 0
String list = null;
for (int i = 0; i < children.size(); i++) {
list = children.get(i);
}
return name + " Parent: " + parent + " Children: " + list;
Here you are iterating over all children, take the name of the last children in the list and return it together with the parents name.
Besides: please check if children can also be of class Person

Related

Calendar order in java [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
public class FileDAO extends DaoBase implements ITreeDao {
File rootDirectory = null;
public FileDAO(File rootDirectory) {
if(!rootDirectory.exists()){
throw new IllegalArgumentException("Directory " + rootDirectory.getAbsolutePath() + " doesn't exist");
}
this.rootDirectory = rootDirectory;
}
protected ITreeNode readRoot(ITree tree) {
tree.setRoot(readNode(this.rootDirectory));
TreeSorter.sortById(tree.getRoot());
return tree.getRoot();
}
protected Set readChildren(ITreeNode parentNode) {
Set children = new HashSet();
File parentDir = (File) parentNode.getObject();
String[] files = parentDir.list();
if(files == null) return children;
for(int i=0; i<files.length; i++){
File childFile = new File(parentDir.getAbsolutePath() + File.separator + files[i]);
ITreeNode child = readNode(childFile);
child.setParentId(parentNode.getId());
if(!childFile.exists()) continue;
children.add(child);
}
// Sort here
TreeSorter.sortById(parentNode);
return children;
}
protected Set readGrandChildren(ITreeNode parentNode) {
Set grandChildren = new HashSet();
Iterator children = parentNode.getChildren().iterator();
while(children.hasNext()){
ITreeNode child = (ITreeNode) children.next();
grandChildren.addAll(readChildren(child));
}
return grandChildren;
}
protected ITreeNode readNode(File file){
if(!file.exists()) return null;
ITreeNode node = null;
String childType = file.isDirectory() ? "directory" : "file";
if(childType.equals("file")){
node = new TreeNode(file.getAbsolutePath(), "<a href=\"openPdf.jsp?fileName=" + file.getAbsolutePath() + "\" target=_blank>" + file.getName() + "</a>" , childType);
}else{
node = new TreeNode(file.getAbsolutePath(), file.getName() , childType);
}
node.setObject(file);
return node;
}
}
In this code am facing one issue at readGrandChildren() method. Like there I'm getting calendar months ascending order but I want to display calendar order like Jan,Feb,Mar.....Dec.
Please can anyone help me?
Thanks&Regards,
Venkat.
https://github.com/business-logic/br4j/blob/master/base/SharedComponents/Controls/src/com/jenkov/prizetags/tree/impl/FileDao2.java
use TreeSet, by implementing Comparator interface and providing reverse sorting logic and finally add all elements of HashSet to TreeSet using addAll() method of Collection interface.
// using Comparator constructor argument of TreeSet
TreeSet < String > ts = new TreeSet < String > (new Comparator < String > () {
#Override
public int compare(String o1, String o2) {
// reverse sorting logic
return o2.compareTo(o1);
}
});
// add HashSet elements to TreeSet
ts.addAll(grandChildren);
System.out.println("\n\n\nAfter Sorting : Descending order\n");
// Iterating using Iterator
Iterator < String > ascSorting = ts.iterator();
while (ascSorting.hasNext()) {
System.out.println(ascSorting.next());
}

How to write a remove method to get rid of object from arraylist

I'm trying to make a program in java that you can add people's birthdays, names, birthmonths, and birthyears. I'm having a hard time trying to come up with the code to remove an object from the arraylist here is the following code. How would I go about writing the removePerson method?
import java.util.ArrayList;
public class Analyzer {
// instance variables - replace the example below with your own
private final static int DAYS_PER_MONTH = 31;
private final static int MONTHS_PER_YEAR = 12;
private int[] birthDayStats;
private int[] birthMonthStats;
private ArrayList<Person> people;
/**
* Constructor for objects of class Analyzer
*/
public Analyzer() {
this.people = new ArrayList<Person>();
this.birthDayStats = new int[Analyzer.DAYS_PER_MONTH];
this.birthMonthStats = new int[Analyzer.MONTHS_PER_YEAR];
}
public void addPerson(String name, int birthDay, int birthMonth, int
birthYear) {
Person person = new Person(name, birthDay, birthMonth, birthYear);
if (person.getBirthDay() != -1 || person.getBirthMonth() != -1) {
people.add(person);
birthMonthStats[birthMonth - 1]++;
birthDayStats[birthDay - 1]++;
} else {
System.out.println("Your current Birthday is " + birthDay + " or "
+ birthMonth + " which is not a correct number 1-31 or 1-12 please " +
"put in a correct number ");
}
}
public void printPeople() { //prints all people in form: “ Name: Tom Month: 5 Day: 2 Year: 1965”
int index = 0;
while (index < people.size()) {
Person person = (Person) people.get(index);
System.out.println(person);
index++;
}
}
public void printMonthList() { //prints the number of people born in each month
// Sample output to the right with days being similar
int index = 0;
while (index < birthMonthStats.length) {
System.out.println("Month number " + (index + 1) + " has " +
birthMonthStats[index] + " people");
index++;
}
}
public Person removePerson(String name) {// removes the person from the arrayList
}
}
/**
* Removes the {#code Person} with the given {#code name} from the list
* #param name the {#code Person}'s name
* #return the {#code Person} removed from the list or {#code null} if not found
*/
public Person removePerson(String name) {
if (name != null) {
for (Iterator<Person> iter = people.iterator(); iter.hasNext(); ) {
Person person = iter.next();
if (name.equalsIgnoreCase(person.getName())) {
iter.remove();
return person;
}
}
}
return null;
}
See the java.util.Iterator#remove() method.
Tuesday learning bonus:
If you want to look for a name faster in your list, you should consider to use a java.util.Map implementation:
HashMap<String,Person> people;
You can add Person objects in a smart way in order to make your search case insensitive:
people.put(name.toLowerCase(), new Person(name, ...));
... and your removePerson method become:
public Person removePerson(String name) {
if (name != null)
name = name.toLowerCase();
return people.remove(name);
}
See the java.util.Map#remove() method.
If you are using Java 1.8. It's pretty simple way to do. This will remove Person having 'name' from your list.
people.removeIf(x -> name.equalsIgnoreCase(x.getName()));

Error in IndexOutOfBoundsException using Loop from Database another class Java

I'm getting an java.lang.IndexOutOfBoundsException. This is my code:
Main.java:
for (int i = 0; i < ordersList.size(); i++) {
if (ordersList.get(i).getUser_id() == ordersList.get(i)
.getPersonsList().get(i).getId()) {
System.out.println("Order: "
+ ordersList.get(i).getId()
+ "Person"
+ ordersList.get(i).getPersonsList().get(i)
.getName());
}
}
Database.java:
MysqlPrepareStat = MysqlConn.prepareStatement(insertQueryStatement);
ResultSet result = MysqlPrepareStat.executeQuery();
while (result.next()) {
Orders orders = new Orders();
orders.setId(result.getInt("o.id"));
orders.setDate(result.getString("o.date_time"));
orders.setQuantity(result.getInt("o.quantity"));
Person persons = new Person();
orders.setUser_id(result.getInt("u.id"));
persons.setName(result.getString("u.name"));
persons.setSobrename(result.getString("u.sobrename"));
persons.setEmail(result.getString("u.email"));
persons.setId(result.getInt("u.id"));
persons.setCellphone(result.getInt("u.telefone"));
orders.addPerson(persons);
orderList.add(orders);
}
I want to get the Persons with the same id from Orders that i have declared inside orderList
public List<Person> getPersonsList() {
return personsList;
}
public void addPerson(Person person) {
personsList.add(person);
}
if (ordersList.get(i).getUser_id() == ordersList.get(i)
.getPersonsList().get(0).getId())
You are adding PersonList to each order and that PersonList has only one person for each order. So It is advised to do get(0) rather than get(i).
Please fix code inside your Main.java:
for (int i = 0; i < ordersList.size(); i++) {
if (ordersList.get(i).getUser_id() ==
ordersList.get(i).getPersonsList().get(0).getId()) {
System.out.println("Order: "+ ordersList.get(i).getId()+
"Person"+ ordersList.get(i).getPersonsList().get(0).getName());
}
}

How to pass Different object variables which is getters in the below code for loop?

How to pass Different variables which is getters in the below codes for loop???
public class HtmlTags extends Employee {
public HtmlTags() {
}
static HtmlTags htags;
static String[][] tags = { { "<tr>", "</tr>" }, { "<th>", "</th>" },
{ "<td>", "</td>" }, { "<>", "</>" } };
String tag;
public HtmlTags(int sno, String empName, int days, String tag) {
super(sno, empName, days);
this.tag = tag;
}
public static String htmlAppend(String tag) {
Employee emp = new Employee(1, "balaji", 10);
String result = "";
int row = tags.length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < 2; j++) {
if (tag.equals(tags[i][j])) {
row = i;
break;
}
}
}
if (row == HtmlTags.tags.length) {
result += "search failed to return any results";
} else {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 1; j++) {
result += HtmlTags.tags[row][j] + emp.getEmployeeName()
+ HtmlTags.tags[row][j + 1];
}
}
}
return result;
}
}
output is:
tr balaji /tr tr balaji /tr tr balaji /tr
expected output:
tr balaji /tr tr 1 /tr tr 10 /tr
i need to pass employee variables(getters ) one by one. Any help experts?
You can use something like this in the else block
if (row == HtmlTags.tags.length) {
result += "search failed to return any results";
} else {
result = HtmlTags.tags[row][0] + emp.getEmployeeName()
+ HtmlTags.tags[row][1];
result += HtmlTags.tags[row][0] + emp.getEmployeeSNo()
+ HtmlTags.tags[row][1];
result += HtmlTags.tags[row][0] + emp.getEmployeeDays()
+ HtmlTags.tags[row][1];
}
Please note: you code is awfully "low-level". This means that you are using many concepts that, yes work; but that require a lot of small details to work.
For example: don't use a two dimensional array. Instead, you could create a real class for HtmlTags; something that works like:
class HtmlTag {
private final String tagName;
HtmlTag(String tagName) { this.tagName; }
String embedInTag(String message) {
return "<" + tagName + "> " + message + "</" + tagName +">";
}
Meaning: good programming is all about creating useful abstractions. Your code doesn't abstract anything; and I am tempted to say: therefore your code itself is really rally abstract, complex, hard to read, and will be hard to maintain over time.
Finally: you made HtmlTag a child class of Employee. From an OO perspective, that is absolutely horrible. You see, good OO design is much more than just putting extends here or the because it seems convenient! Instead inheritance is about "child is a parent". And, no, a HtmlTag is never an Employee!
There are a lot of important concepts to know and understand, and if you miss those, the code that you create .. well, looks like the mess you are showing here. This is not meant to be rude, just a hint that you seriously should look into such topics! One starting point: SOLID design principles.

Logic of deleting in Java

I cant figure out how to start a method to delete a specific entry stored in an array...
I used to do this:
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
}
}
}
but I was advised not to assign the entry[i] to null because it will ruin my entries...
I have no idea how to code it in another way...
What should I need to do is:
I need to delete a specific entry from an array
please help...
also... its output was error it says:
Exception in thread "main" java.lang.NullPointerException
at AddressBook.viewAll(AddressBook.java:62)
at AddressBook.main(AddressBook.java:36)
Java Result: 1
This is my code in my main program:
public class AddressBook {
private AddressBookEntry entry[];
private int counter;
private String SName;
public static void main(String[] args) {
AddressBook a = new AddressBook();
a.entry = new AddressBookEntry[100];
int option = 0;
while (option != 5) {
String content = "Choose an Option\n\n"
+ "[1] Add an Entry\n"
+ "[2] Delete an Entry\n"
+ "[3] Update an Entry\n"
+ "[4] View all Entries\n"
+ "[5] View Specific Entry\n"
+ "[6] Exit";
option = Integer.parseInt(JOptionPane.showInputDialog(content));
switch (option) {
case 1:
a.addEntry();
break;
case 2:
a.deleteEntry();
break;
case 3:
a.editEntry();
break;
case 4:
a.viewAll();
break;
case 5:
a.searchEntry();
break;
case 6:
System.exit(1);
break;
default:
JOptionPane.showMessageDialog(null, "Invalid Choice!");
}
}
}
public void addEntry() {
entry[counter] = new AddressBookEntry();
entry[counter].setName(JOptionPane.showInputDialog("Enter name: "));
entry[counter].setAdd(JOptionPane.showInputDialog("Enter add: "));
entry[counter].setPhoneNo(JOptionPane.showInputDialog("Enter Phone No.: "));
entry[counter].setEmail(JOptionPane.showInputDialog("Enter E-mail: "));
counter++;
}
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
for (int i = 0; i < counter; i++) {
addText = addText + entry[i].getInfo() + "\n";
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
public void searchEntry() {
int notfound = 0;
SName = JOptionPane.showInputDialog("Enter Name to find: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, entry[i].getInfo2());
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
notfound = 0;
}
public void editEntry() {
int notfound = 0;
SName = JOptionPane.showInputDialog("Enter Name to edit: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
entry[i] = new AddressBookEntry();
entry[i].setName(JOptionPane.showInputDialog("Enter new name: "));
entry[i].setAdd(JOptionPane.showInputDialog("Enter new add: "));
entry[i].setPhoneNo(JOptionPane.showInputDialog("Enter new Phone No.: "));
entry[i].setEmail(JOptionPane.showInputDialog("Enter new E-mail: "));
break;
} else {
notfound++;
}
}
if (notfound != 0) {
JOptionPane.showMessageDialog(null, "Name Not Found!");
}
notfound = 0;
}
public void deleteEntry() {
SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int i = 0; i < counter; i++) {
if (entry[i].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[i] = null;
break;
}
}
}
}
Assigning the values to null is going to be the easiest practice. If you're really picky, you could resize the array, but that would be rather pointless. Just keep a separate size counter and decrement it each time you set something to null.
Another reason you're getting a null pointer exception is that you have to consider what's happening when you're replacing values in your array with null but still iterating by counter. You're going to be left with holes in your array upon deletion. The first solution would be to bypass null values altogether, and just shift your array down (somewhat of an expensive operation). The second would be to alter your methods to take those null values into consideration. Example:
public void viewAll() {
String addText = " NAME\tADDRESS\tPHONE NO.\tE-MAIL ADD\n\n";
int nonNull = 0;
for (int i = 0; i < entry.length; i++) {
if (entry[i] != null) {
addText = addText + entry[i].getInfo() + "\n";
nonNull++;
}
if (nonNull == counter) break;
}
JOptionPane.showMessageDialog(null, new JTextArea(addText));
}
I don't have a compiler on this computer, so consider it more of psuedo-code. But the idea is that the counter is only keeping track of how many non-null values you have in your address book, and that these null values could be in random places of your array. I added the nonNull integer as a local counter to keep track of how many values you've encountered that aren't null (so you aren't forced to run through the entire address book). Then, I added the if statement to ensure that the value at entry[i] isn't a null value (trying to invoke getInfo() on a null value is what's giving you that error). Lastly, I added the if statement to break the loop if you've encountered all of the non-null values you have stored. Hope this helps. (Also it may be worth considering a LinkedList to eliminate the null values all together).
Actually, for simplicity's sake, you probably are much better off using a LinkedList, unless you are required to use an array, since you would need to alter all of your methods to take null spaces in your array into account. Assuming you're familiar with LinkedLists of course.
Arrays are immutable. You can change the value for a particular index in the array but you can't change the array size itself. To "delete", you could do:
myArray[index] = null;
And just treat null values as unset/deleted entries.
Assigning to null (currently what you are doing) is the proper thing to do. That will eliminate the reference to the object at that index and allow it to be garbage collected.
Replace entry[i] = null; with this:
System.arraycopy(entry, i + 1, entry, i, counter - i - 1);
--counter;
entry[counter] = null; // optional; helps with garbage collection
--i; // required to not skip the next element
(I'm assuming here that counter is the number of valid entries in entry. This will leave no null entries among the first counter elements of entry (assuming that there weren't any to start with).
Further thought: If you need the array length to always match the number of valid entries, you'll have to re-allocate the array and copy the values over. Just use arraycopy to copy entries from 0 through i-1 and from i+1 to counter-1 into the new array and then assign it to entry. This isn't particularly efficient and is best avoided if possible.
Better to this is List which has remove() method. But if you really want use Array I recommend you change Array to List and then remove all values, after it you can always change List to Array
import javax.swing.JOptionPane;
public class Test {
private static User[] entry = new User[] { new User("Gil"),
new User("Bil"), new User("John") };
public static void main(String... args) {
final Test test = new Test();
test.deleteEntry();
for (int index = 0; index < entry.length; index++) {
User user = entry[index];
if (user != null)
System.out.println(entry[index]);
}
}
public void deleteEntry() {
String SName = JOptionPane.showInputDialog("Enter Name to delete: ");
for (int index = 0; index < entry.length; index++) {
if (entry[index].getName().equals(SName)) {
JOptionPane.showMessageDialog(null, "Found!");
entry[index] = null;
break;
}
}
}
private static class User {
private String name;
public User(String name) {
this.name = name;
}
/**
* #return the name
*/
public String getName() {
return name;
}
#Override
public String toString() {
return name;
}
}
}

Categories