简体   繁体   中英

Why is there a missing method error even when the code block is never called?

I'm writing a Mad Libs program. In it, there are a variety of stories.. or at least there will be. At the moment, there's only one. But my method that chooses a story has reference to methods I haven't made yet. For some reason, this code will not compile, even though at no point am I calling the unmade methods. Why is this?

Here's the choose a story method.

public void chooseStory (int choice)
    {
        switch (choice)
        {
        case 1:
            story1();
            break;
        case 2:
            story2();
            break;
        case 3:
            story3();
            break;
        case 4:
            story4();
            break;
        }

But even if choice is 1, I still get the error:

Exception in thread "main" java.lang.Error: Unresolved compilation problems: 
    The method story2() is undefined for the type MLServer
    The method story3() is undefined for the type MLServer
    The method story4() is undefined for the type MLServer

    at MLServer.chooseStory(MLServer.java:13)
    at MLApp.main(MLApp.java:31)

Why is the JVM evaluating code that's never hit?

Java doesn't know what code will be called. You might aswell upload and use the class-files from a server for example. Apart from that it would be pretty complicated (or even impossible, if user-choices are involved) to predicate which parts of the code will be accessed and which not. And the resulting byte-code would contain references to code that doesn't even exist, which would make compilation and execution pretty complicated.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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