-3

我正在做一个使用 OOP 的作业。该程序本质上将根据用户输入的内容创建一堆不同的狐猴。它们都具有 Parent 类的相似特征以及它们自己类中的独特特征。

该程序的一部分是允许用户决定要创建的对象(或狐猴)的数量。我想以渐进的方式创建对象,所以 L1、L2、L3 ......等等。

这是我到目前为止所拥有的。所以我基本上想使用 lemCounter 来跟踪狐猴编号并将其附加到对象名称,每次创建新对象时。

//Main section of code

static int numLems, typeLems, loop, lemCounter;
static String allLems[];
public static void main(String[] args) {
    //Ask for the number of lemurs
    askNL();
    //Initalize the length of the array to the total number of lemurs
    allLems = new String[numLems];
    //Ask which lemurs the user wants to generate
    //Set the lemur counter and the lemur string to nothing
    lemCounter = 0;
    for(int i = 0; i < numLems; i++){
        //Run the method that asks which lemur they want
        askTL();
        //Run the method to check which lemur the user wanted
        checkTL();
        //Use lemCounter to keep track of the lemur number
        lemCounter++;
    }
}


//Method asking how many lemurs, for the sake of cleaniness in the main method

static int askNL(){
    do{
        try{
            String numLemsStr = JOptionPane.showInputDialog("How many Lemurs would you like to generate?");
            numLems = Integer.parseInt(numLemsStr);
            loop = 2;
        }
        catch(NumberFormatException e){
            JOptionPane.showMessageDialog(null, "Not an acceptable input, please try again.");
            loop = 1;
        }
    }while(loop==1);
    return numLems;
}

//Method asking which type of Lemur

static int askTL(){
    do{
        try{
            String typeLemsStr = JOptionPane.showInputDialog("What type of Lemur would you like for Lemur "+ lemCounter+1
                    + "\n1 - Tree Lemur"
                    + "\n2 - Desert Lemur"
                    + "\n3 - Jungle Lemur");
            typeLems = Integer.parseInt(typeLemsStr);
            if(typeLems > 3){
                JOptionPane.showMessageDialog(null, "Not an acceptable input, please try again.");
                loop = 1;
            }
            else{
                loop = 2;
            }
        }
        catch(NumberFormatException e){
            JOptionPane.showMessageDialog(null, "Not an acceptable input, please try again.");
            loop = 1;
        }
    }while(loop==1);
    return typeLems;
}

//Method to decide which lemur the user wanted
static String[] checkTL(){
    if(typeLems==1){
//I'm not sure what I need to put in the name to get it to proceed linearly
        TreeLemur L = new TreeLemur();
    }
    return allLems;
}
4

1 回答 1

2

不要将存在但并不像您想象的那么重要的变量名称与不存在的对象“名称”混淆。例如,假设您可以根据数字给出变量名称,并且具有:

Lemur lemur1 = new Lemur();
Lemur lemur2 = lemur1;

那么这里被“命名”的狐猴对象的“名称”是什么?狐猴1还是狐猴2?请注意,它们都引用同一个Lemur 对象。

使用数组,或者ArrayList<Lemur>如果您想要可以按数字访问的 Lemurs 的顺序集合。Map<String, LemurL>如果您想让 Lemur 与字符串相关联,请使用 a 。

于 2013-05-13T02:44:35.303 回答