簡體   English   中英

沒有主要方法時,程序如何運行

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

我正在我的大學學習Java課程,並且正在使用一個名為acm的庫。 但是,當我們編寫代碼時,我們不會創建main方法。 “ public void run(){}”充當主要方法。 請解釋。

例如,這是我創建的程序。

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);

                    }
                }
            }
        }
    }
}

事情已經提供了主要方法。 在您的情況下,幾乎可以肯定是您的類可以擴展的ACM內容( ConsoleProgram ),並在某個時候調用您的run方法。

因為:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM