2013-05-13 303 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