无法使用方法和变量从静态上下文引用非静态方法
在编写BookStoreApplication时,它使用Book,Tape和CD类来创建对象。 虽然未完成,但应用程序类应创建新的BookStoreItems,即Book,Tape和CD。 它们inheritance自BookStoreItems类。 在这个应用程序类中,我不断收到错误:
error: non-static method printMenu() cannot be referenced from a static context error: non-static method getUserChoice() cannot be referenced from a static context error: non-static variable input cannot be referenced from a static context
我把它改为静态然后不是静态的,但我继续得到这个错误……
import java.util.Scanner; public class BookStoreApp2 { //constants for options static final int ADD_BOOK = 0; static final int ADD_TAPE = 1; static final int ADD_CD = 2; static final int QUIT = -1; Scanner input = new Scanner (System.in); public static void main(String[] args) { BookStoreItem[] item;//declaring array item = new BookStoreItem[10];//initializing array int itemType = -1; printMenu(); getUserChoice(); for (int i = 0; i < item.length; i++){ System.out.print("\n" + i + "\tEnter 0 for Book, 1 for Tape, 2 for CD: "); itemType = input.nextInt(); switch (itemType) { case 0: item[i] = new Book(); break; case 1: item[i] = new Tape(); break; case 2: item[i] = new CD(); break; default: System.out.println("\nInvalid choice."); }//end of switch statement }//end of for loop for (int i = 0; i < item.length; i++) { System.out.println("\nAnimal #" + i + ": "); System.out.println("\n\tTitle: " + item[i].getTitle()); //polymorphic because they can operate on separate objects System.out.println("\n\tAuthor: " + item[i].getAuthor()); }//end of for }//end of main method //PRINT MENU---------------------------------------------------------- public void printMenu(){ System.out.println("\nPress:"); System.out.println("\t" + ADD_BOOK + "\tTo add a book to the book store.\n"); System.out.println("\t" + ADD_TAPE + "\tTo add a tape to the book store.\n"); System.out.println("\t" + ADD_CD + "\tTo add a CD to the book store.\n"); System.out.println("\t" + QUIT + "\tTo exit\n"); } //--------------------------------------------------------------------- //GET USER CHOICE------------------------------------------------------ public int getUserChoice() { int choice; System.out.print("Please enter your choice: "); choice = input.nextInt(); return choice; }//end of getUserChoice //---------------------------------------------------------------------- }//end class
你需要同时使你的方法 – printMenu()
和getUserChoice()
static
,因为你是直接从static main
方法调用它们而不创建类的实例,这些方法是定义的。你不能调用non-static
方法,不引用它们所定义的类的实例。
或者,您可以将方法调用部分更改为:
BookStoreApp2 bookStoreApp = new BookStoreApp2(); bookStoreApp.printMenu(); bookStoreApp.getUserChoice();
仅仅为了使您的程序工作,请获取main()方法的内容并将它们放在构造函数中:
public BookStoreApp2() { // Put contents of main method here }
然后,在main()方法中。 做这个:
public void main( String[] args ) { new BookStoreApp2(); }
你也可以
1)声明printMenu()
, getUserchoice()
并输入为static
要么
2)如果您想更好地设计它,请将逻辑从main
移动到单独的实例方法中。 然后从main
创建一个新类的实例并调用您的实例方法
您应该放置Scanner input = new Scanner (System.in);
进入main方法而不是在外面创建输入对象。