繁体   English   中英

当方法不是静态的时,为什么会说它是静态的?

[英]Why does it say it is static when the method isn't static?

我试图为理论视频商店制作面向对象的库存系统。

我不断收到以下错误消息:

non-static variables xyz cannot be accessed from a static context.

我在静态上下文中找到的所有信息都是针对一种方法是静态的而另一种方法不是静态的,但是我的方法都不是静态的。

在这段代码中,我两次收到该错误消息,但我不明白为什么。

if (enterOption == 1) {
    Movie movieNew = new Movie (titleInput, yearInput, directorInput, ratingInput, genreInput);
    VideoShop.movies.add(movieNew);  
} else {
    UI.runUI();
}

我从VideoShop.movies.add(movieNew); UI.runUI(); 方法调用。

完整方法:

public void createMovie ()
{
    Scanner sc = new Scanner (System.in);

    System.out.println ("Title: ");
    String titleInput = sc.next();

    System.out.println ("Year: ");
    int yearInput = sc.nextInt();

    System.out.println ("Director: ");
    String directorInput = sc.next();

    System.out.println ("Rating [G / PG / M / MA15 / R18]: ");
    String ratingInput = sc.next();

    System.out.println ("Genre [a - Action/ b - Drama/ c - Comedy/ d - Musical/ e - Family/ f - Documentary]: ");
    String genreInput = sc.next();

    System.out.println ("Format [VCD/DVD]: ");
    String formatInput = sc.next();

    System.out.println ("Cost: ");
    double costInput = sc.nextDouble(); 

    System.out.println ("Quantity: ");
    int quantityInput = sc.nextInt();


    System.out.println("Confirm?");
    System.out.println("1. Yes 2. No, return to main menu");

    System.out.println("Enter option: ");
    int enterOption = sc.nextInt();

    if (enterOption == 1) {
        Movie movieNew = new Movie (titleInput, yearInput, directorInput, ratingInput, genreInput);
        VideoShop.movies.add(movieNew);

    } else {
        UI.runUI();
    }
}

VideoShop.movies可能是非静态字段。 而不是使用VideoShop.movies您应该创建一个对象:

VideoShop shop = new VideoShop();
shop.movies.add(movieNew);

UI相同:

UI ui = new UI();
ui.runUI();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM