简体   繁体   中英

Seperate one array into two arrays based on the class's values. JAVA

So I have three classes, Person , GroupOfPeople and a Main class.

Class person:

public class Person {
    
    private String name;
    private int age;
    private char gender;
    private double weight;

    public char getGender() {
        return gender;
    }
    
    public void setGender(char gender) {
        this.gender = gender;
    }
    
    ... other getters and setters respectively
}

As you can see the Person class has an instance variable of gender. In GroupOfPeople I created an array of persons as followed:

private Person[] personGroup = new Person[5];

This stores all persons, no matter their gender. What I want is a method that separates the men from all the other persons in the array.

Therefore I've created the method findMen() that looks like this:

public void findMen() {
        int counter = 0;
        Person[] allMen = new Person[5];
        
        while (counter < personGroup.length) {
            if (personGroup[counter].getGender() == 'M') {
                allMen[counter] = personGroup[counter];
            } else {
                break;
            }
            counter++;
        }
        
        System.out.println("All the men are:");
        for (int i = 0; i < allMen.length; i++) {
            if (allMen[i] != null) {
                System.out.println(allMen[i].getName());
            }
        }
    }

This is not working, it only adds 1 person to the allMen array, while I've defined more men in my main method:

GroupOfPeople gop = new GroupOfPeople();
        
        Person p1 = new Person();
        p1.setName("Person 1");
        p1.setAge(40);
        p1.setGender('M');
        
        Person p2 = new Person();
        p2.setName("Person 2");
        p2.setAge(30);
        p2.setGender('F');
        
        Person p3 = new Person();
        p3.setName("Person 3");
        p3.setAge(20);
        p3.setGender('M');

        gop.findMen();

The output is:

All the men are:
Person 1

While the expected output is:

All the men are:
Person 1
Person 3

I hope you can give me some insights as to what I'm doing wrong.

Your break statement is incorrectly placed. it breaks the first time you do not get a man. Break when you have gone over the whole length of the personGroup.

Nevermind, solved it...

Person[] allMen = new Person[5];

for (int i = 0; i < personGroup.length; i++) {
            if (personGroup[i] != null) {
                if (personGroup[i].getGender() == 'M') {
                    for (int j = 0; j < allMen.length; j++) {
                        if (allMen[j] == null) {
                            allMen[j] = personGroup[i];
                            break;
                        }
                    }
                }
            }
        }

The problem is here. Get rid of the break;

 while (counter < personGroup.length) {
        if (personGroup[counter].getGender() == 'M') {
              allMen[counter] = personGroup[counter];
        } else {
                break;  // get rid of this, you stop if no M is found. 
        }
            counter++;
  }

Try it like this

while (counter < personGroup.length) {
        if (personGroup[counter].getGender() == 'M') {
              allMen[counter] = personGroup[counter];
        } 
        counter++;
}

The break is causing it to end the loop as soon as you find a female. The reason you get a NullPointerException when you remove that is because of the use of your arrays

ArrayList<Person> allMen = new ArrayList<Person>();
  for(Person p : personGroup){
    if(p.getGender() == 'M') allMen.add(p);
}

Finally, to iterate and output men just do the same thing:

for(Person p : allMen){
  System.out.println(p.getName());
}

Your else body contains a break . That means that the loop finishes when a person other than a man is found. You probably want to use continue here (or drop the else entirely).

I have, however, two suggestions:

List

Use a List instead of an array. A widely-used implementation of the List interface is the ArrayList . The advantage is that the list is dynamically-sized. That means that you can add an unlimited amount of items to the list without knowning the capacity beforehand.

// Convert the array to a list, if necessary. However, I suggest you replace all arrays
// with lists
List<Person> allPersons = Arrays.asList(personGroup);

List<Person> men = new ArrayList<>();
for (Person p : allPersons) {
    if (p.getGender() == 'M') {
        men.add(p);
    }
}

Streams

Java 8 was shipped with the Streams API. This could make your code even more concise.

List<Person> men = allPersons.stream() // Stream over all persons
    .filter(p -> p.getGender() == 'M') // Select only men
    .collect(Collectors.toList());     // Put them into a List

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM