java - 替代调用 main

标签 java loops

我遇到这个问题,如果用户说"is",我会尝试重新开始游戏,并且我总是通过调用 main() 来做到这一点,但我的老师坚持认为有更好的方法。如何在不调用 main 的情况下启动程序?我假设您必须使用循环,但我不确定如何使用它来解决这个问题。

        //import library
    import java.io.*;
    import java.util.*;

    //file name
    public class GuessingGame
    {
        //Main method, throws input and output error.
        public static void main (String [] args) throws IOException
        {
            //inputs for random number and switch statements
            Scanner inRn = new Scanner (System.in);
            Scanner inSw = new Scanner (System.in);

            //variables for the loop, random number, character, counter and input
            int guess=0;
            int rnd;
            int num;
            char decision;

        //random number generator
        Random random = new Random();
        rnd = random.nextInt(100) + 1;

        //loops the user input for the guess
        while (true){
            try{
                //prompt the user
                System.out.println(" Please guess a number between 1-100. Press 0 to give up.");
                num = inRn.nextInt();
            }
            //catches input errors 
            catch (Exception e){ 
                System.out.println("You can only enter numbers!");
                inRn.next();
                continue;
            }

        //if statements
        if (num==0) 
        {
            //when user types '0' it ends the program
            System.out.println("You gave up after " + guess + " try(s)  .... Closing program ...");
            System.exit(0);
        }
        else if (num>rnd) 
        {



                System.out.println("The number is too big!"); 
                guess++;
            }
            else if (num<rnd)
            {
                //prints 'too small', adds to counter 'guess'
                System.out.println("The number is too small!"); 
                guess++;
            }
            else 
            {
                //prints correct, adds to counter, dsiplays # of guesses and ends loop
                System.out.println("You guessed the right number!!: " + rnd); 
                guess++; 
                System.out.print(" # of guesses: " + guess + " -");

                //loops the case untill correct input is chosen either 'Y' or 'N'
                while(true){

                    //prompt the user if they want to play again
                    System.out.println(" Would you like to play again? <Y/N>");
                    decision = inSw.nextLine().charAt(0);

                    //switch statements
                    switch (decision) {
                        case 'Y':
                        case 'y':    
                            //calls main, basically restarts the game
                            GuessingGame.main(args);     
                            break;

                        case 'N':
                        case 'n':
                            System.out.println("Bye!");
                            //exits the program completely
                            System.exit(0);
                            break;

                        default: 
                            //if incorrect input, this prints
                            System.out.println("Please enter a Yes or No <Y/N>");
                    }
                }
            }
        }   
    }
}

最佳答案

我记得在编程课上,我的老师告诉我要避免使用 while(true) 语句。

无论如何,有一个专门为这种行为设计的循环,它称为 do-while loop 。在main方法中用with调用main方法称为递归调用。它们有它们的位置,它们可以完成其他循环无法完成的工作。

这里的问题是每个方法调用都有它自己的局部变量,当你再次调用main时,它仍然会记住上一场比赛以及之前的每场比赛的所有结果。这看起来并没有那么糟糕,尤其是如果您稍后使用该信息的话。更大的问题是递归循环不能像 for 或 while 循环那样被无限次调用。每次调用 main 时存储的局部变量都存储在堆栈中。当堆栈填满时,您会得到 StackOverflowError 。如果你想看到这种情况发生,请创建一个像这样的 main 方法:

public static void main(String args[])
{
    main(args);
}

以下是 do-while 循环的示例:

Scanner in = new Scanner(System.in);
char decision;
do{
    //game code ...
    do{
        System.out.print("Do you wish to continue? (y,n): ");
        decision = in.nextLine().charAt(0);
    }while(!(decision == 'y' || decision == 'n'));
}while(decision == 'y');

一些很酷的递归用途:

Factorial

Fibonacci sequence

关于java - 替代调用 main,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26795053/

相关文章:

java - Spring Data Rest - 无法更新(PATCH)引用另一个实体的子实体列表

r - 循环遍历向量的向量

基于向量元素运行循环

javascript - 使用 JavaScript Prototype 库循环遍历所有选择元素

php - 如何迭代 mysql 数组并从 PHP 数组追加相应的文本

java - Java中的对象列表

java - 如何对角线移动可见图像?

java - PLS-00103 : Encountered the symbol "TEST_PKG" when expecting one of the following: ;

jvm - 需要服务器 VM 但在 JRE 中不可用。那我需要什么包: JRE, JDK呢?

c++ - 如何在C++中进行无限循环? ( Windows )