简体   繁体   English

根据类的值将一个数组分成两个数组。 爪哇

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

So I have three classes, Person , GroupOfPeople and a Main class.所以我有三个类, PersonGroupOfPeople和一个Main类。

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.如您所见,Person 类有一个性别实例变量。 In GroupOfPeople I created an array of persons as followed:GroupOfPeople我创建了一组人员,如下所示:

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:因此,我创建了findMen()方法:

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:这不起作用,它只向allMen数组添加了 1 个人,而我在主方法中定义了更多人:

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.您的 break 语句放置不正确。 it breaks the first time you do not get a man.第一次你没有得到一个男人时它会中断。 Break when you have gone over the whole length of the personGroup.当您遍历完整个 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删除时出现 NullPointerException 的原因是因为使用了数组

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:最后,迭代和输出 man 只需做同样的事情:

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

Your else body contains a break .您的 else 正文包含一个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).您可能想在此处使用continue (或完全删除else )。

I have, however, two suggestions:不过我有两个建议:

List列表

Use a List instead of an array.使用List而不是数组。 A widely-used implementation of the List interface is the ArrayList . List接口的一个广泛使用的实现是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. Java 8 附带了 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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