Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 8 of 8

Thread: Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

  1. #1
    Junior Member
    Join Date
    Mar 2019
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

    I have a project to submit and need help correcting the errors in my code. The error message states "non static method cannot be called from a static context." I have no idea how to correct this code. I have reached out to a few tutors and the last one did not respond and now I am out of time. Please help! I have attached the code

    RecipeBox issue.txt

  2. #2
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

    To call a non-static method, the code needs to have a reference to an instance of the class and use that reference to call the method:
       refToClass.theMethodToCall();  // call non-static method

    To call a static method, use the classname dot method name:
      TheClassName.theStaticMethod();  // call static method

    Please post here any code that you are asking about. Not as an attachment or link.
    If you don't understand my answer, don't ignore it, ask a question.

  3. The Following User Says Thank You to Norm For This Useful Post:

    bigrich08 (March 3rd, 2019)

  4. #3
    Junior Member
    Join Date
    Mar 2019
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

    Thank you I tried to post my code initially but it gave me an error so I ended up having to attach it so in this case its referencing a method called addNewRecipe in another class called Recipe. I currently have it as this.listOfRecipes.add(Recipe.addNewRecipe());. Based on what you are saying should it be changed to this this.listOfRecipes.add(RecipeBox.addNewRecipe());? ?

    See full code below:

    package Final;

    import java.util.ArrayList;

    /**
    *
    * @author rijackson
    */
    public class RecipeBox {
    //Single private instance field
    private ArrayList<Recipe> listOfRecipes;

    /**
    *Constructor for recipe box
    */
    public RecipeBox() {
    this.setListOfRecipes(new ArrayList<>());
    }

    /**
    *
    * @param listOfRecipes
    */
    public RecipeBox(ArrayList<Recipe> listOfRecipes) {
    this.setListOfRecipes(listOfRecipes);
    }



    //Accessor and mutator for list of recipes
    /**
    *
    * @return list of recipes
    */
    public ArrayList<Recipe> getListOfRecipes() {
    return listOfRecipes;
    }

    /**
    *
    * @param listOfRecipes the list of recipes
    */
    public void setListOfRecipes(ArrayList<Recipe> listOfRecipes) {
    this.listOfRecipes = listOfRecipes;
    }


    /**
    * method to add new recipe to the collection
    */
    public void addNewRecipe() {
    //call into static method on recipe class
    this.listOfRecipes.add(Recipe.addNewRecipe());
    }

    //print all recipe names

    /**
    * Method to print all recipe names
    */
    public void printAllRecipeNames() {
    for(Recipe r : listOfRecipes) { //iterate over list
    System.out.println(r.getRecipeName()); //print the name
    }
    }

    /**
    *
    * @param name
    */
    public void printRecipeDetails(String name) {
    Recipe r = findRecipe(name); //look for recipe
    if(r == null) { //if none found, notify user
    System.out.println("Recipe not found");
    } else {
    r.printRecipe();//print full details
    }
    }

    /**
    *
    * @param name
    */
    public void deleteRecipe(String name) {
    Recipe r = findRecipe(name); //find recipe by name
    if(r == null) { //if no match, notify user
    System.out.println("Recipe not found");
    } else {
    listOfRecipes.remove(r); //remove recipe from list
    }
    }

    //helper to find a recipe by name
    //Returns null if no match is found
    private Recipe findRecipe(String name) {
    for(Recipe r : listOfRecipes) {
    if(r.getRecipeName().equals(name)) {
    return r;
    }
    }
    return null;
    }
    }

    --- Update ---

    Thank you I tried to post my code initially but it gave me an error so I ended up having to attach it. So in this case its referencing a method called addNewRecipe in another class called Recipe. I currently have it as this.listOfRecipes.add(Recipe.addNewRecipe());. Based on what you are saying should it be changed to this this.listOfRecipes.add(RecipeBox.addNewRecipe());? ?

    See full code below:
    package Final;
     
    import java.util.ArrayList;
     
    /**
     * 
     * @author rijackson
     */
    public class RecipeBox {
    	//Single private instance field
    	private ArrayList<Recipe> listOfRecipes;
     
         /**
         *Constructor for recipe box
         */
    	public RecipeBox() {
    		this.setListOfRecipes(new ArrayList<>());
    	}
     
        /**
         * 
         * @param listOfRecipes
         */
        public RecipeBox(ArrayList<Recipe> listOfRecipes) {
    		this.setListOfRecipes(listOfRecipes);
    	}
     
     
     
          //Accessor and mutator for list of recipes
        /**
         *
         * @return list of recipes
         */
    	public ArrayList<Recipe> getListOfRecipes() {
    		return listOfRecipes;
    	}
     
        /**
         *
         * @param listOfRecipes the list of recipes
         */
        public void setListOfRecipes(ArrayList<Recipe> listOfRecipes) {
    		this.listOfRecipes = listOfRecipes;
    	}
     
     
        /**
         * method to add new recipe to the collection
         */
    	public void addNewRecipe() {
                //call into static method on recipe class
                this.listOfRecipes.add(Recipe.addNewRecipe());
    	}
     
    	//print all recipe names 
     
        /**
         * Method to print all recipe names
         */
    	public void printAllRecipeNames() {
    		for(Recipe r : listOfRecipes) { //iterate over list
    			System.out.println(r.getRecipeName()); //print the name
    		}
    	}
     
        /**
         * 
         * @param name
         */
    	public void printRecipeDetails(String name) {
    		Recipe r = findRecipe(name); //look for recipe
    		if(r == null) { //if none found, notify user
    			System.out.println("Recipe not found");
    		} else {
    			r.printRecipe();//print full details
    		}
    	}
     
        /**
         *
         * @param name
         */
        public void deleteRecipe(String name) {
    		Recipe r = findRecipe(name); //find recipe by name
    		if(r == null) { //if no match, notify user
    			System.out.println("Recipe not found");
    		} else {
    			listOfRecipes.remove(r); //remove recipe from list
    		}
    	}
     
    	//helper to find a recipe by name
    	//Returns null if no match is found
    	private Recipe findRecipe(String name) {
    		for(Recipe r : listOfRecipes) {
    			if(r.getRecipeName().equals(name)) {
    				return r;
    			}
    		}
    		return null;
    	}
    }
    Last edited by bigrich08; March 3rd, 2019 at 05:03 PM. Reason: wrapping code

  5. #4
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

       this.listOfRecipes.add(Recipe.addNewRecipe());
    What class is the method addNewRecipe defined in? The Recipe class was not posted.
    Is there a reference to an instance of that class that is available when you want to call the method?

    The syntax of the expression: Recipe.addNewRecipe() says that addNewRecipe is a static method in the Recipe class.



    Please edit your post and wrap your code with code tags:

    [code]
    **YOUR CODE GOES HERE**
    [/code]

    to get highlighting and preserve formatting.
    If you don't understand my answer, don't ignore it, ask a question.

  6. #5
    Junior Member
    Join Date
    Mar 2019
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

    its in my recipe class See Below


    public class Recipe {
     
        private String recipeName;
        private int servings;    
        private List<Ingredient> recipeIngredients;
        private double totalRecipeCalories;    
     
        /**
         *
         */
        private List<Recipe> listofRecipes = new ArrayList<>();
     
        /**
         * 
         * @return the recipeName
         */
        //accessors and mutators
        public String getRecipeName() {
    		return recipeName;
    	}
     
        /**
         *
         * @param recipeName
         */
        public void setRecipeName(String recipeName) {
    		this.recipeName = recipeName;
    	}
     
        /**
         *
         * @return
         */
        public int getServings() {
    		return servings;
    	}
     
        /**
         *
         * @param servings
         */
        public void setServings(int servings) {
    		this.servings = servings;
    	}
     
        /**
         *
         * @return
         */
        public List<Ingredient> getRecipeIngredients() {
    		return recipeIngredients;
    	}
     
        /**
         *
         * @param recipeIngredients
         */
        public void setRecipeIngredients(List<Ingredient> recipeIngredients) {
    		this.recipeIngredients = recipeIngredients;
    	} 
     
        /**
         *
         * @return the total recipe calories
         */
        public double getTotalRecipeCalories() {
    		return totalRecipeCalories;
    	}
     
        /**
         *
         * @param totalRecipeCalories
         */
        public void setTotalRecipeCalories(double totalRecipeCalories) {
    		this.totalRecipeCalories = totalRecipeCalories;
    	}
     
     
     
     
        /**
         * default constructor
         */
        public Recipe() {
            this.recipeName = "";
            this.servings = 0;
            this.recipeIngredients = new ArrayList <>();
            this.totalRecipeCalories = 0;
     
        }
        //overloaded constructor to create custom recipe
     
        /**
         *
         * @param recipeName
         * @param servings
         * @param recipeIngredients
         * @param totalRecipeCalories
         */
        public Recipe(String recipeName, int servings, 
        	ArrayList<Ingredient> recipeIngredients, double totalRecipeCalories) {
            this.recipeName = recipeName;
            this.servings = servings;
            this.recipeIngredients = recipeIngredients;
            this.totalRecipeCalories = totalRecipeCalories;
        }
     
     
        /**
         *  method to print recipe
         */
        public void printRecipe() {
        		int singleServingCalories = 0;
        		singleServingCalories = (int) (this.getTotalRecipeCalories()/this.getServings());
     
        		System.out.println("Recipe: " + this.getRecipeName());
        		System.out.println("Serves: " + this.getServings());
            System.out.println("Ingredients: ");
            for(Ingredient ingredients : getRecipeIngredients()) {
            		System.out.println("Ingredient name: " + ingredients.getnameOfIngredient() );
            		System.out.println("Ingredient Amount: " + ingredients.getingredientAmount() );        		
            		System.out.println(" Calories with measurement: "
                                    + ingredients.unitMeasurement + "Each serving has " + singleServingCalories);
            }   
        }
     
        /**
         *
         * @return add new recipe per user inputs
         */
     
        public Recipe addNewRecipe() {
            double totalRecipeCalories = 0.0;
     
            boolean addMoreIngredients = true;
     
            Scanner scnr = new Scanner(System.in);
     
            System.out.println("Please enter the recipe name: ");
            String recipeName = scnr.nextLine();
     
            System.out.println("Please enter the number of servings: ");
            int servings = scnr.nextInt();
             /**
              * 
              */       
            do {
                Ingredient thisIngredient = new Ingredient();
                System.out.println("Please enter the ingredient name "
                		+ "or type end if you are finished entering ingredients: ");
                String ingredientName = scnr.next();
                if (ingredientName.toLowerCase().equals("end")) {
                    addMoreIngredients = false;  // "end" discomtinues the loop
                } else {
                	    thisIngredient.setnameOfIngredient(ingredientName); //adding ingredient to recipe list
     
     
    	            System.out.println("Please enter the ingredient amount: "); //prompt to enter the ingredient amount
    	            float ingredientAmount = scnr.nextFloat();  
    	            thisIngredient.setIngredientAmount(ingredientAmount);
     
    	            System.out.println("Please enter the ingredient Calories: "); //prompt to enter the ingredient calories
    	            int ingredientCalories = scnr.nextInt();
    	            thisIngredient.setNumberOfCaloriesPerIngredient(ingredientCalories);
     
    	            //Add the total Calories from this ingredient 
    	            totalRecipeCalories = totalRecipeCalories + (ingredientCalories * ingredientAmount);      
    	            getRecipeIngredients().add(thisIngredient);
                }
     
     
           } while (addMoreIngredients); //looping to add ingredients from user unless "end" 
                    //create new recipe with user inputs 
                    Recipe recipe;
                    recipe = new Recipe(recipeName,servings, (ArrayList<Ingredient>) getRecipeIngredients(), totalRecipeCalories);
                    recipe.printRecipe();
                    return recipe;
     
     
        }
     
        /**
         * @return the listofRecipes
         */
        public List<Recipe> getListofRecipes() {
            return listofRecipes;
        }
     
        /**
         * @param listofRecipes the listofRecipes to set
         */
        public void setListofRecipes(List<Recipe> listofRecipes) {
            this.listofRecipes = listofRecipes;
        }

  7. #6
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

    The addNewRecipe() method is not static, so it can not be called using the static syntax as I mentioned above.

    Can it be changed to a static method?

    Otherwise there needs to be a reference to an instance of the Recipe class that can be used as I mentioned above.
    If you don't understand my answer, don't ignore it, ask a question.

  8. The Following User Says Thank You to Norm For This Useful Post:

    bigrich08 (March 3rd, 2019)

  9. #7
    Junior Member
    Join Date
    Mar 2019
    Posts
    5
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Default Re: Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

    ahh ok I changed it to static and that removed the error message there but then it placed that same error message on this part of the code in the Recipe class now which is referring to the getRecipeIngredients() accsessor.
     
    	            //Add the total Calories from this ingredient 
    	            totalRecipeCalories = totalRecipeCalories + (ingredientCalories * ingredientAmount);      
    	            [COLOR="#FF0000"]getRecipeIngredients().add(thisIngredient);[/COLOR]
                }
     
     
           } while (addMoreIngredients); //looping to add ingredients from user unless "end" 
                    //create new recipe with user inputs 
                   [COLOR="#FF0000"] Recipe recipe = new Recipe(recipeName,servings, (ArrayList<Ingredient>) getRecipeIngredients(), totalRecipeCalories);[/COLOR]
                    recipe.printRecipe();
                    return recipe;
     
     
        }
    Could you give me an example of what an instance of the Recipe class would look like in this case? that may be what I need vs making the method static.
    Last edited by bigrich08; March 3rd, 2019 at 08:23 PM. Reason: highlighting text

  10. #8
    Super Moderator Norm's Avatar
    Join Date
    May 2010
    Location
    Eastern Florida
    Posts
    25,139
    Thanks
    65
    Thanked 2,720 Times in 2,670 Posts

    Default Re: Please help with correcting error "NON STATIC METHOD CANNOT BE CALLED FROM STATIC CONTEXT"

    example of what an instance of the Recipe class would look like
    An instance of a class is created with a new statement that calls the class's constructor. The following statement from your code creates an instance of the Recipe class and saves the reference in the recipe variable:
     Recipe recipe = new Recipe(recipeName,servings, (ArrayList<Ingredient>) getRecipeIngredients(), totalRecipeCalories);

    same error message on this part of the code in the Recipe class
    You can not make a method static if it uses other parts of the class that are not static.
    The ingredients for a recipe belong to one recipe so their values can not be static (meaning shared between all instances of a class).

    Look at where the original problem is. What recipe is it working with? The code needs a reference to that recipe so it can call one of its methods.
    If you don't understand my answer, don't ignore it, ask a question.

Similar Threads

  1. [SOLVED] Need help desperately: "non-static variable this cannot be referenced from a static context"
    By mikbferguson in forum What's Wrong With My Code?
    Replies: 1
    Last Post: October 2nd, 2017, 08:27 PM
  2. Replies: 6
    Last Post: May 3rd, 2013, 04:25 PM
  3. Replies: 4
    Last Post: November 15th, 2012, 12:09 AM
  4. Replies: 9
    Last Post: November 5th, 2011, 10:22 AM
  5. Replies: 10
    Last Post: September 6th, 2010, 04:48 PM