简体   繁体   中英

How does my program run when I don't have a main method

I am studying java course in my college and we are using a library called acm. But when we write a code we don't create a main method. "public void run(){}" acts as a main method. Explain please.

For an example here's a program that I created.

import acm.program.ConsoleProgram;
import acm.util.RandomGenerator;

public class Assignment3 extends ConsoleProgram {

    private static final long serialVersionUID = 1L;
    private RandomGenerator rgen = RandomGenerator.getInstance();

    public void run() {
        final int QUESTION_AMOUNT = 5;

        println("Welcome to the Math Quiz! You have " + QUESTION_AMOUNT + " questions to answer! Good luck!");

        for (int i = 0; i < QUESTION_AMOUNT; i++) {
            askQuestion();
        }

        println("End of the quiz!");
    }

    public void askQuestion() {
        int num1, num2, kidanswer, realanswer;
        String operation = "";
        boolean x = rgen.nextBoolean();

        if (x == true) {
            operation = "+";
        } else {
            operation = "-";
        }

        if (operation == "-") {
            num1 = rgen.nextInt(0, 20);
            num2 = rgen.nextInt(0, num1);
        } else {
            num1 = rgen.nextInt(0, 20);
            num2 = rgen.nextInt(0, 20 - num1);
        }

        String question = ("What is " + num1 + " " + operation + " " + num2 + " = ");

        if (operation == "-") {
            realanswer = num1 - num2;
        } else {
            realanswer = num1 + num2;
        }

        kidanswer = readInt(question);

        int i = 0;
        while (i < 2) {
            if (kidanswer == realanswer) {
                println("That is correct! Well done!");
                break;
            } else {
                kidanswer = readInt("Wrong answer. Please try another answer: ");
                i++;
                if (i == 2) {
                    if (kidanswer == realanswer) {
                        println("That is correct! Well done!");
                    } else {
                        println("Sorry :( Out of tries! The answer was: " + realanswer);

                    }
                }
            }
        }
    }
}

Something has to provide a main method. In your case, it's almost certainly going to be the ACM stuff ( ConsoleProgram ) which your class extends and which will, at some point, call your run method.

Because:

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