問題描述
使用並行數組和用戶輸入 (Using Parrallel array and user input)
對於我的程序,我必須創建一堆方法,但我堅持啟動它。基本上是一個存儲樹木類型和種子數量的程序。我有一個數組中的樹列表,並希望將每棵樹的種子數放在一個平行數組中,我覺得我採取了正確的步驟,但並沒有真正得到正確的邏輯。
import javax.swing.JOptionPane;
public class seedFarmer {
public static void main(String[] args) {
}
public static int getNumEachTree() {
String[] treeTypes = {"Fir" , "Pine" , "Spruce"};
int[] numTrees = new int[treeTypes.length];
int numofTrees = getNumEachTree();
for (int index = 0; index < numTrees.length; index++) {
numTrees[index] = Integer.parseInt(JOptionPane.showInputDialog("Enter the number of seeds you want to plant for: " + treeTypes[index]));
}
return numTrees;
}
}
參考解法
方法 1:
You're main problem is here:
public static int getNumEachTree() {
String[] treeTypes = {"Fir" , "Pine" , "Spruce"};
int[] numTrees = new int[treeTypes.length];
int numofTrees = getNumEachTree(); <‑‑HERE
You are calling getNumEachTree() causing a recursive habit that never ends. The function will never stop calling itself as it has no check for whether to call itself or not and so will loop forever.
Also you are never using numofTrees so why break your code with it? I assume it is supposed to be the return value? Maybe you intended on calling that function from main? You are returning numTrees when you should be returning an int, not an array of ints.
I don't understand what the purpose of this code is entirely but just a few syntax point outs. Your logic seems okay.
(by Javabegin、Phyreprooph)