Java non-static method addInv(int) cannot be referenced from a static context

前端 未结 4 1478
有刺的猬
有刺的猬 2021-01-26 08:09

I know this error very well however this is the once time I\'m stumped. I know that I can\'t call non-static variables from main method but this is confusing. Maybe you can help

4条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-26 08:34

    You can't call a non static method from a static method. So either make addInv static:

    public class Item {
        ...
    
        public static void main(String args[]) {
            addInv(1);
        }
    
        public static void addInv(int e) {
            ...
        }
    
        public static String[] getItem(int e) {
            ...
        }
    }
    

    But making all these methods static may not be an appropriate design, you might prefer using an Item instance in your main:

    public class Item {
        ...
    
        public static void main(String args[]) {
            Item item = new Item();
            item.addInv(1);
        }
    
    }
    

    By the way, I don't mean to be rude but you should seriously work on your (awful) code formatting and conventions, both for readers and for you.

    See also

    • Code Conventions for the Java Programming Language
    • How to Write Doc Comments for the Javadoc Tool

提交回复
热议问题