这样做的正确方法是什么?

时间:2015-02-07 05:46:39

标签: java arrays scope

我知道这一定是一个基本的设计问题,因为我显然不能这样做。我想根据分配给OwnedSpirits(int)的整数值从另一个类调用ownGrokk,ownTyce等方法。这反过来填充阵列。

问题是,我多次执行此操作,并且从另一个类执行此操作似乎每次都必须创建一个新对象以传递新的int参数,这样做会重置spiritInstance的值。并且,由于重置为零,因此阵列无法正确填充。我尝试稍后打印出我的数组值,然后得到一个“ArrayIndexOutOfBoundsException”。

public class OwnedSpirits {       
    private int spiritTypeInt = 0;

    public static int spiritInstance=0;                                                  
    public static int[] spiritarray = new int[9];
    public static String[] spiritName = new String[9];
    public static int[] party = new int[3];

    public OwnedSpirits(int spiritcall){
        if(spiritcall == 1){
            ownGrokk();
        }     
        if(spiritcall == 2){
            ownRisp();
        }
        if(spiritcall == 3){
            ownTyce();
        }
        if(spiritcall == 4){
            ownDaem();
        }
        if(spiritcall == 5){
            ownCeleste();
        }
    }

    private void ownGrokk(){ 
        spiritName[spiritInstance] = "Grokk";
        spiritInstance++;                
    }

    private void ownRisp(){     
        spiritName[spiritInstance] = "Risp";
        spiritInstance++;              
    }

    private void ownDaem(){ 
        spiritName[spiritInstance] = "Daem";
        spiritInstance++;      
    }

    private void ownCeleste(){ 
        spiritName[spiritInstance] = "Celeste";
        spiritInstance++;          
    }

    private void ownTyce(){ 
        spiritName[spiritInstance] = "Tyce";
        spiritInstance++; 
    }

并且此代码在另一个类中,它尝试调用方法来填充数组

buttonConfirm.addListener(new ClickListener(){
    @Override
    public void clicked(InputEvent event, float x, float y) {                                
        if(xcounter==3){
            for(x=0; x<3; x++){
                if(setdaemtrue == true){
                    new OwnedSpirits(4);
                }
                if(setrisptrue == true){
                    new OwnedSpirits(2);
                }
                if(setcelestetrue == true){
                    new OwnedSpirits(5);
                }
                if(settycetrue == true){
                    new OwnedSpirits(3);
                }
                if(setgrokktrue == true){
                    new OwnedSpirits(1);
                }    
            }
        }
    }
});   

最后在另一个班级:

System.arraycopy(OwnedSpirits.spiritName, 0, partylist, 0, 3);

@Override
public void show() {
    System.out.println(partylist[0]);
    System.out.println(partylist[1]);
    System.out.println(partylist[2]);

    spiritlist.setItems(partylist);
    table.add(spiritlist);
    table.setFillParent(true);
    stage.addActor(table);      
}

如果最后一部分令人困惑,那是因为我使用的是libgdx。打印语句只是为了弄清楚我的列表出错的原因

1 个答案:

答案 0 :(得分:1)

我可以告诉你我将如何处理烈酒和派对。 Spirit类包含其分配给的名称和当前方:

package com.stackoverflow.spirit;

public class Spirit {
    private String name;
    private Party party;
    private SpiritType type;
    private static int id = 0;

    public static enum SpiritType {
        Grokk, Risp, Tyce, Daem, Celeste
    };

    public Spirit(String name, SpiritType type) {
        create(name, type);
    }

    public Spirit(SpiritType type) {
        create(null, type);
    }

    // This is to handle Java inexistance of default parameter values.
    private void create(String name, SpiritType type)
    {
        Spirit.id++;

        this.name = (name == null) ? (type.name() + " " + id) : name;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public Party getParty() {
        return party;
    }

    public SpiritType getType() {
        return type;
    }

    /**
     * Used internally by @see Party
     * @param party the party this Spirit belongs
     */
    public void setParty(Party party) {
        this.party = party;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString()
    {
        return this.name;
    }
}

最后,Party类包含一组Spirits,你可以在派对中添加和删除Spirits。

package com.stackoverflow.spirit;

import java.util.HashSet;

public class Party {
    private HashSet<Spirit> spirits = new HashSet<Spirit>();
    private static int id = 0;
    private String name = "Party " + Party.id++;;

    public Party() {
    }

    public Party(String name) {
        this.name = name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void add(Spirit spirit) {
        if (!spirits.contains(spirit)) {
            spirits.add(spirit);

            if (spirit.getParty() != null) {
                //Remove from previous party to update the other party set
                spirit.getParty().remove(spirit);
            }
            spirit.setParty(this);
        } else {
            // throw new SpiritAlreadyOnParty();
        }
    }


    public void remove(Spirit spirit)
    {
        if (spirits.contains(spirit))
        {
            spirit.setParty(null); // You could create a default empty party for "Nature/Neutral" Spirits perhaps :)
            spirits.remove(spirit);
        }
        else {
            //throw new SpiritNotInParty();
        }
    }

    public boolean isOnParty(Spirit spirit) {
        return spirits.contains(spirit);
    }

    public ArrayList<Spirit> getSpirits()
    {
        return new ArrayList<Spirit>(spirits);
    }

    public int getPartySize() {
        return spirits.size();
    }

    public String getPartyInfo()
    {
        StringBuilder builder = new StringBuilder();

        builder.append("Party:" + this.name + " Size:" + this.spirits.size() + "\n");
        for (Spirit s : spirits)
        {
            builder.append(s.getName() + "\n");
        }
        return builder.toString();
    }


    @Override
    public String toString()
    {
        return this.name;
    }
}

在这里,我使用Spirit和Party类,你可以添加更多功能,比如派对力量,派对上的魔法爱好者等等:

package com.stackoverflow.spirit;

import com.stackoverflow.spirit.Spirit.SpiritType;

public class Main {
    public static void main(String[] args) throws java.lang.Exception {
        Party griffindor = new Party("Griffindor"), slytherin = new Party(
                "Slytherin");

        // You can also do for (SpiritType type : SpiritType.values() then
        // type.ordinal()
        for (int i = 0; i < SpiritType.values().length; i++) {
            griffindor.add(new Spirit(SpiritType.values()[i]));
            slytherin.add(new Spirit(SpiritType.values()[i]));
        }

        Spirit mySpirit = new Spirit("NotAHPFan", SpiritType.Celeste);

        slytherin.add(mySpirit);

        System.out.println("Name of party:" + mySpirit.getParty().getName());
        System.out.println("Is on griffindor?:"
                + griffindor.isOnParty(mySpirit));

        // What now?
        griffindor.add(mySpirit);
        System.out.println("Is " + mySpirit.getName() + " on "
                + slytherin.getName() + "?:" + slytherin.isOnParty(mySpirit));

        System.out.println(mySpirit.getName() + " is now on "
                + mySpirit.getParty() + "\n");


        System.out.println(griffindor.getPartyInfo());
        System.out.println(slytherin.getPartyInfo());
    }
}
P.D:我不是惠普的粉丝。