2013-05-13 177 views
-2

我正在使用OOP进行分配。该程序基本上会根据用户的输入内容创建一系列不同的狐猴。它们都具有来自父级的类似特征以及他们自己班级中的独特特征。用变量命名变量

该程序的一部分是允许用户决定要创建的对象(或狐猴)的数量。我想以渐进的方式创建对象,所以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

什么问题? – Nikki 2013-05-13 02:43:09

+0

-1未能清楚地陈述问题。 – 2013-05-13 02:44:00

+0

您不能使用计算名称创建变量。相反,你应该使用数组或ArrayList。 – Blorgbeard 2013-05-13 02:44:18

回答

2

不要混淆变量其存在,但如你有对象“名”不存在认为是几乎没有重要的。例如,假设你可以给基于数字的变量名和有:

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

那么什么是狐猴对象的“名”被“命名”在这里? lemur1还是lemur2?请注意,它们都是指相同的狐猴物体。

如果您想要按序号访问的狐猴顺序集合,请使用数组或ArrayList<Lemur>。如果您想让狐猴与字符串关联,请使用Map<String, LemurL>

+1

有趣的部分是,OP(有点)有这样的数组 - 'allLems' – 2013-05-13 02:48:30