我正在使用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;
}
什麼問題? – Nikki 2013-05-13 02:43:09
-1未能清楚地陳述問題。 – 2013-05-13 02:44:00
您不能使用計算名稱創建變量。相反,你應該使用數組或ArrayList。 – Blorgbeard 2013-05-13 02:44:18