-2

有这个:

static class Girl{
    public String age;
    public String name;
    public String id;
}

static Girl[] girl;

然后我无法在我的主要功能中执行此操作:

ResultSet r = s.executeQuery("select count(*) from children");   
r.next();
girl_count=r.getInt(1);
girl = new Girl[girl_count];

r = s.executeQuery("select * from children");   
int i = 0;
while(r.next()){
    i = r.getString("id");
    if(girl[i]==null)girl[i]=new Girl();
    girl[i].age=r.getString("age");
    girl[i].name=r.getString("name");
    girl[i].id=r.getString("id");
}

上面的代码不起作用,我想要实现的是:

System.out.println(girl[3]);

特别是这一行:

 girl = new Girl[girl_count];

谁能帮我更正这段代码?- 或者找出我在这里缺少什么?

4

2 回答 2

5

Java 最佳实践表明你的类名应该以大写字母开头,并且你的变量/字段名应该是小写的。我相信,在这种情况下,您的代码无法编译,因为您有一个名为“girl”的类和一个同名的变量。

将您的班级更改为大写字母:

static class Girl{ ...}

然后从那里去。错误消息也将更容易理解。

于 2013-09-17T19:40:16.083 回答
0

来自评论:您需要一个地图来实现您想要实现的目标:

Map<Integer, Girl> girls = new HashMap<Integer, Girl>();

while(r.next()){
    int i = r.getInt("id"); // note the getInt()
    Girl g = girls.get(i); //attempt to get girl from map by ID, returns null if not found

    if(g==null) { // check if null
        g=new Girl(); // create
        girls.put(i,g); //put into map
    }
    g.age=r.getString("age");
    g.name=r.getString("name");
    g.id=r.getString("id");
}

当您想要访问地图的元素时:

Girl found = girls.get(id); //id is an Integer

遍历 Girl 实例:哇,我刚刚写了我写的吗???我有老婆!

for(Girl girl: girls.values()) {
   System.out.println(girl.name); //here you can do anything to the Girl, what morality permits...

}

此外,您可以使用该方法对键进行迭代.keySet()

或者,如果您也想要 ID:

for(Map.Entry<Integer,Girl> entry: girls.entrySet()) {

   Integer id = entry.getKey();
   Girl girl = entry.getValue();
   System.out.println(girl.name); //here you can do anything to the Girl, what morality permits...

}

然而,行为是,当结果集中有更多具有相同 id 的女孩时(无论如何都不可能),它会覆盖所述女孩的属性,使其不确定......

于 2013-09-17T19:46:54.780 回答