用变量命名变量

时间:2013-05-13 02:35:54

标签: java arrays

我正在开发一个使用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;
}

1 个答案:

答案 0 :(得分:2)

不要混淆存在的变量 name ,但这与您认为不存在的对象“name”的重要性差不多。例如,假设您可以根据数字给出变量名称并且具有:

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

那么在这里“命名”的狐猴对象的“名称”是什么? lemur1或lemur2?请注意,它们都引用了相同的狐猴对象。

如果您想要一个可以通过数字访问的狐猴序列集合,请使用数组或ArrayList<Lemur>。如果您想让狐猴与一个字符串相关联,请使用Map<String, LemurL>