2015-01-24 7 views
-4

Функция findRecipe возвращает объект, который содержит в себе имя String, после того как я захватил возвращенный объект и использовал метод getName() для отображения его имени String, но он показывает нулевой указатель Exception..why? Я первый вопрос размещения вопрос .., если не детали. спасибоКак увидеть содержимое полученного объекта?

public class Cookbook { 

private Recipe listOfRecipes[] = new Recipe[100]; 
private static int numberOfRecipes = 0; 

public void setListOfRecipes(Recipe a) 
{ 
    listOfRecipes[numberOfRecipes] = a; 
    numberOfRecipes++; 
} 

public Recipe[] getListOfRecipes() 
{ 
    return listOfRecipes; 
} 

public void addRecipe(Recipe b) 
{ 
    Recipe temp[] = new Recipe[listOfRecipes.length]; 
    int count = 0; 

    for(int i = 0; i < listOfRecipes.length; i++) 
    { 
     temp[i] = listOfRecipes[i]; 
     count++; 
    } 

    temp[count] = b; 
} 

public Recipe findRecipe(String c) 
{ 
    Recipe temp1 = new Recipe(); 
    Recipe temp2[] = new Recipe[numberOfRecipes - 1]; 
    for(int j = 0; j < temp2.length; j++) 
    { 
    temp2[j] = listOfRecipes[j]; 
    } 

    String a; 
    for(int i = 0; i < temp2.length; i++) 
    { 
     a = temp2[i].getName(); 
     if(c.equals(a)) 
     { 
      temp1 = temp2[i]; 
     } 
     else 
     { 
      temp1 = null; 
     } 
    } 

    return temp1; 
} 

public static void main(String[]args) 
{ 
    Recipe butterCake = new Recipe("ButterCake"); 

    butterCake.setIngredients("3 cup butter"); 
    butterCake.setIngredients("4 1/2 cup flour"); 
    butterCake.setIngredients("3 cup sugar"); 
    butterCake.setIngredients("4 eggs"); 

    butterCake.setInstructions("Add butter with flour"); 
    butterCake.setInstructions("Mix butter and flour"); 
    butterCake.setInstructions("Now add 3 cup sugar"); 
    butterCake.setInstructions("Mix 4 eggs until yellow pale colour appears"); 
    butterCake.setInstructions("Bake the mixture for 30 minutes"); 

    System.out.println(butterCake.getName()); 
    butterCake.numberOfInstructions(); 
    butterCake.numberOfIngredients(); 
    butterCake.showIngredients(); 
    butterCake.showInstructions(); 

    Recipe vanillaCake = new Recipe("VanillaCake"); 

    vanillaCake.setIngredients("3 cup butter"); 
    vanillaCake.setIngredients("4 1/2 cup flour"); 
    vanillaCake.setIngredients("3 cup sugar"); 
    vanillaCake.setIngredients("4 eggs"); 

    vanillaCake.setInstructions("Add butter with flour"); 
    vanillaCake.setInstructions("Mix butter and flour"); 
    vanillaCake.setInstructions("Now add 3 cup sugar"); 
    vanillaCake.setInstructions("Mix 4 eggs until yellow pale colour appears"); 
    vanillaCake.setInstructions("Bake the mixture for 30 minutes"); 

    System.out.println(vanillaCake.getName()); 
    vanillaCake.numberOfInstructions(); 
    vanillaCake.numberOfIngredients(); 
    vanillaCake.showIngredients(); 
    vanillaCake.showInstructions(); 

    Cookbook cookBook1 = new Cookbook(); 

    cookBook1.setListOfRecipes(butterCake); 
    cookBook1.setListOfRecipes(vanillaCake); 

    Recipe q[] = new Recipe[2]; 
    q = cookBook1.getListOfRecipes(); 
    System.out.println(q[0].getName()); 
    System.out.println(q[1].getName()); 

    Recipe y = new Recipe(); 

    y = cookBook1.findRecipe("VanillaCake"); 

    System.out.println(y.getName()); // ------> GIVING ERROR 

    } 
} 

output : 

run: 
Name of the Recipe: ButterCake 
Number of instructions: 5 
Number of ingredients: 4 

Ingredients: 
1. 3 cup butter 
2. 4 1/2 cup flour 
3. 3 cup sugar 
4. 4 eggs 

Instructions: 
1. Add butter with flour 

Exception in thread "main" java.lang.NullPointerException 
2. Mix butter and flour 
3. Now add 3 cup sugar 
at Cookbook.main(Cookbook.java:120) 
4. Mix 4 eggs until yellow pale colour appears 
5. Bake the mixture for 30 minutes 
Name of the Recipe: VanillaCake 
Number of instructions: 5 
Number of ingredients: 4 

Ingredients: 
1. 3 cup butter 
2. 4 1/2 cup flour 
3. 3 cup sugar 
4. 4 eggs 

Instructions: 
1. Add butter with flour 
2. Mix butter and flour 
3. Now add 3 cup sugar 
4. Mix 4 eggs until yellow pale colour appears 
5. Bake the mixture for 30 minutes 
Name of the Recipe: ButterCake 
Name of the Recipe: VanillaCake 
Java Result: 1 
BUILD SUCCESSFUL (total time: 0 seconds) 
+2

??????????????? – Typo

+0

'System.out.println (c);' это то, что вам нужно? или вы хотите увидеть контент Reciepe? Если нет, то не понятно, что вы после? – SMA

+0

... печать его в консоли? Или создать веб-приложение? Или приложение Swing? Или приложение JavaFX? Или приложение для Android? –

ответ

1

Задача 1: Вы не нарушая, как только вы найдете матч. Таким образом, только когда вы вернете ненулевое значение, это когда встречается последний индекс.

Добавить break после того, как встречается совпадение.

Задача 2: Ваша getName функция в классе Recipe возвращается как Name of the Recipe: RECIPE NAME

Решение: Либо изменить способ getName возвращает имя рецепта (избавиться от Name of the Recipe:) или изменить способ вызова.

Модифицированный for loop в функции getRecipe

String a; 
temp1=null; 
for(int i = 0; i < temp2.length; i++) 
{ 
    a = temp2[i].getName(); 
    if(c.equals(a)) 
    { 
     temp1 = temp2[i]; 
     break; //<---------- 
    } 
    else 
    { 
     temp1 = null; 
    } 
} 

return temp1; 
} 

вызывать эту функцию, как (в основной)

y = cookBook1.findRecipe("Name of the Recipe: VanillaCake"); 
Смежные вопросы