2015-11-10 46 views
-1

好吧,所以這可能是一個漫長的,但目前我堅持如何在這種情況下爲每個新配方創建Ingrediants列表,因爲當我運行這兩個程序截至目前它不斷地添加對象到相同的名單。任何建議縮短代碼或更好的方法將不勝感激,但爲每個迭代做一個實例變量是最重要的。謝謝。爲了澄清,我每次運行AddRecipe類時都需要一個特定於該配方的新成分的新列表,而不是所有配方中的大量Ingrediants。如何在每次for循環命中時創建一個對象列表?

問題;每次我遍歷我的addIngrediant類時,我都希望爲使用它的AddRecipe類創建一個獨特的元素值。 (對於每一個配方,新的Ingrediants)我不知道如何做到這一點,並提供了兩種方法的樣本。

在配方類

public static void addIngrediants(String EcipeName){ 
    if(Recipe.recipeName.equals(EcipeName)){ 
    List<List<String>> lists = new ArrayList<List<String>>(); 
    for (int i = 0; i < 100; i++) { 

System.out.println("Would you like to add an Ingrediant(YES or NO)"); 
Scanner yesSir = new Scanner(System.in); 
String inputSir = yesSir.nextLine(); 

if(inputSir.equals("YES")){ 
System.out.println("Enter your Ingrediant; "); 
String userIngred = yesSir.nextLine(); 
Ingred.add(userIngred); 

System.out.println("Your Ingrediant is; " + userIngred); 
System.out.println("Your new ingrediant list is now; " + Ingred); 

    } 
else{ 
    System.out.println("Okay thanks!"); 
    break; 
} 
} 
} 


} 

在包裝類提前

public static void AddRecipe(){ 
    Recipe jackson = new Recipe(); 
    int index = 0; 
    for(int i = 0; i<= recipeBook.size();){ 
     System.out.println("============================"); 
     System.out.println("Welcome to the Recipe Book!"); 
     System.out.println("============================"); 
     jackson.getDirections(); 
     jackson.getCalorieCount(); 
     jackson.getHi(); 
     jackson.getRecipeName(); 



      System.out.println("Would you like to add a recipe?(Type YES or NO)"); 
      Scanner wantTo = new Scanner(System.in); 
      String bad = wantTo.nextLine(); 

      if(bad.equals("YES")){ 
       index++; 
       System.out.println("Great, now lets name your Recipe;"); 
       String yesName = wantTo.nextLine(); 
       jackson.setRecipeName(yesName); 

       System.out.println("First we'll start with Ingrediants, Input as many as you like"); 
       Recipe.addIngrediants(yesName); 



       System.out.println("Moving on, Input your Directions;"); 
       String bud = wantTo.nextLine(); 
       jackson.setDirections(bud); 

       System.out.println("Now input a Calorie Count (Numbers Only!)"); 
       int jman = wantTo.nextInt(); 
       jackson.setCalorieCount(jman); 

謝謝!

+1

我投票關閉是因爲:「尋求調試的問題幫助(」爲什麼不是這個代碼工作?「)必須包含所需的行爲,特定的問題或錯誤以及在問題本身中重現問題所需的最短代碼。沒有明確問題陳述的問題對其他讀者無益。「 – bhspencer

+0

我以爲我對問題非常清楚,但如果它不是不可知的,我會編輯它。 – BobRoss567

回答

0

我不知道我完全理解你的問題。僅僅看看你發佈的一小段代碼,在我看來,你並不真正擁抱面向對象的設計。從閱讀你的問題,我會建議做一個配方類,將存儲配方的所有基本要素。在這裏你應該有一個實例變量來存儲你的步驟列表。從這裏開始,我會創建另一個課程,作爲食譜書。這個類應該能夠創建,存儲和管理配方對象。我將創建的最後一堂課將是一個可以接受用戶輸入的課程。這將是您的程序中最高級的類,並允許用戶通過控制檯輸入實際使用該程序。

+0

這就是我所擁有的,只是爲了簡單而展示了部分課程。我的錯誤是我無法爲每個新配方存儲單個Ingrediants列表。 – BobRoss567

+0

每個配方應該有它自己的唯一列表,如果該列表是配方類的一部分(假設該列表不是靜態的),則每次創建一個新的配方對象時該列表應該爲空。另外,從看看你發佈的程序是不是我所描述的。你的食譜類別不應該要求名稱等,它應該只用於存儲和檢索信息。 –

+0

好的謝謝,如果它的靜態會發生什麼變化?如果你有時間可以給我看一個食譜類的代碼示例嗎? ((對不起,我缺乏知識,2個月到計算機科學)) – BobRoss567