替换主叫

时间:2014-11-07 06:01:21

标签: java loops

我有这个问题,如果用户说是,我试图开始游戏,我总是通过调用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>");
                    }
                }
            }
        }   
    }
}

3 个答案:

答案 0 :(得分:1)

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

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

这里的问题是每个方法调用都有它自己的局部变量,当你再次调用main时,它仍会记住上一个游戏的所有结果,以及之前的每个游戏。哪个看起来不是很糟糕,尤其是如果您以后使用该信息。更大的问题是递归循环不能被称为无限次,如for或while循环。为每次调用main存储的局部变量存储在堆栈中。当堆栈填满时,你得到一个StackOverflowError。如果你想看到这种情况,请制作一个像这样的主要方法:

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

答案 1 :(得分:0)

我已将游戏逻辑移至新的play()方法。此方法返回boolean以指示用户是否想要在游戏结束时继续玩游戏。我在do...while方法中使用main循环至少启动一次游戏,然后检查play()方法的返回值以决定是否继续游戏。< / p>

这样程序将优雅地结束,而不会强制它使用System.exit方法退出。它也不会使用在while(true)循环内调用的递归方法,最终会导致StackOverflowError异常。

public static void main(String[] args) throws IOException {
    boolean keepPlaying = false;

    do {
        keepPlaying = play();
    } while (keepPlaying);
}

private static boolean play() {
    //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 ...");
            return false;
        } 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':
                        // User wants to keep playing
                        return true;
                    case 'N':
                    case 'n':
                        System.out.println("Bye!");
                        //exits the program completely
                        return false;
                    default:
                        //if incorrect input, this prints
                        System.out.println("Please enter a Yes or No <Y/N>");
                }
            }
        }
    }
}

答案 2 :(得分:0)

你的老师没错,你不必再打电话给主人,只需要增强你的算法,你就会得到更好的代码。也许是这样的:

//import library
import java.io.IOException;
import java.util.Random;
import java.util.Scanner;

//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 = -1;
        char decision = 'Y';

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

        // loops the user input for the guess
        do {
            if (num != rnd) {
                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 + " -");
                }
            } else {
                // 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 'N':
                case 'n':
                    System.out.println("Bye!");
                    // exits the program completely
                    System.exit(0);
                    break;
                case 'Y':
                case 'y': 
                    rnd = random.nextInt(100) + 1;
                    break;

                default:
                    // if incorrect input, this prints
                    System.out.println("Please enter a Yes or No <Y/N>");
                }
            }
        } while (decision != 'N' || decision != 'n');
        inRn.close();
        inSw.close();
    }
}

为什么这段代码要好得多,恕我直言,因为这些:

  1. 它只使用一个循环,而你的使用2循环。
  2. 它没有再次调用main函数,这将触发另一个进程在内存中启动,并可能导致内存泄漏。
  3. 它关闭输入扫描仪,而你没有。
  4. 希望这会照亮你的一天,如果有任何错误,我很抱歉。谢谢&amp;问候。