0

在这个简单的示例中,我想创建一个字符串数组,其中填充了每个人在我的数据库中的第一个和最后一个。我知道我遗漏了一些非常明显的东西,因为我一直i在以下循环方法中覆盖。第二只眼睛肯定会有所帮助。

    /**
 * 
 * @return
 */
public String[] buildFullNameContainer(){

    List<Person> allPeople = Person.findAllPeople();
    String[] peopleContainer = new String[] {""};
    String fullName = "";



        for (int i = 0; i < peopleContainer.length; i++) {
            for (Person person : allPeople) {
                fullName = person.getFirstName() + " " + person.getLastName();  
                peopleContainer[i] = fullName; 

            }
        }
    return peopleContainer;
}
4

5 回答 5

4

您的数组始终只有一个元素 - 您应该将其创建为与列表相同的长度。此外,你有两个无缘无故的嵌套循环,我认为fullName变量没有意义。这是我要使用的代码:

String[] peopleContainer = new String[allPeople.size()];

for (int i = 0; i < peopleContainer.length; i++) {
    Person person = allPeople.get(i);
    peopleContainer[i] = person.getFirstName() + " " + person.getLastName();
}
于 2012-06-14T20:13:34.910 回答
3

代替

String[] peopleContainer = new String[] {""};

String[] peopleContainer = new String[allPeople.size()];

另外,编辑你的循环如下:

for(int i = 0; i < peopleContainer.length; i++)
{
    Person person = allPeople.get(i);
    fullName = person.getFirstName() + " " + person.getLastName();  
    peopleContainer[i] = fullName;  
}
于 2012-06-14T20:12:47.163 回答
0

我认为这需要改变:

String[] peopleContainer = new String[] {""};

到:

String[] peopleContainer = new String[allPeople.size()];
于 2012-06-14T20:13:49.653 回答
0

您正在循环您的结果数组,而不是您的源数据集合。您必须首先正确调整数组的大小,然后循环遍历数组或列表的大小。不需要嵌套的 for。

public String[] buildFullNameContainer(){

    List<Person> allPeople = Person.findAllPeople();
    String[] peopleContainer = new String[allPeople.size()];
    for (int i = 0; i < peopleContainer.length; i++) {
        Person person = allPeople.get(i);
        String fullName = person.getFirstName() + " " + person.getLastName();  
        peopleContainer[i] = fullName; 
    }
return peopleContainer;
}
于 2012-06-14T20:15:54.117 回答
0

试试这个。

    List<Person> allPeople = Person.findAllPeople();
    String[] peopleContainer = new String[allPeople.size()];

    for (int i=0;i < allPeople.size();i++;) {
          Person person=allPeople.get(i);
          fullName = person.getFirstName() + " " + person.getLastName();  
          peopleContainer[i] = fullName; 
    }
于 2012-06-14T20:16:46.470 回答