CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Jan 2011
    Location
    Orange County, CA
    Posts
    82

    Angry Simple Yet Annoying Problem

    Background:
    I am suppose to be working on a group project for school using Bluej, but guess who's stuck doing all the work? That's right, me. Well, I have the program (a game of Hangman) nearly complete. There are plenty of bugs to still be worked out, but there is one in particular that I cannot figure out how to solve.

    Question:
    How do you end a console program? I've tried System.exit(0) in varias places in my code, as well as letting the program go back to the drive and have nothing else to execute. In both ways I've tried the window will not close (even if you try to press the X at the top). So is there something I'm messing up on or not understanding? Any help would be appreciated.

    Code:
    Below are my Driver and StartGame class, which I believe are the source of the problem. If I'm incorrect (quite possible), just let me know and post the rest of the code (which is a lot, why I only posted these two classes).

    Driver Class:
    Code:
    /**
     * Driver class for Hang Man.
     */
    public class Driver
    {
        public static void main()
        {
            StartGame game = new StartGame();
            game.mainMenu();
        }
    }
    StartGame Class:
    Code:
    import java.io.*;               //Needed for file operations
    import java.util.Scanner;       //Needed for user input
    
    /**
     * All the menus and game options are called through this class.
     */
    public class StartGame
    {
        private Scanner input = new Scanner(System.in);     //Scanner object to receive user input
        
        private HangMan man;                                //HangMan object for the game
        private Player player1;                             //Player object for player 1
        private Player player2;                             //Player object for player 2
        private Solver ai;                                  //AI that guesses a user's word
    
        private Menu mainMenu = new Menu(1);                //The main menu
        private Menu setUpMenu = new Menu(2);               //The game set-up menu
        private Menu gameMenu = new Menu(3);                //The in-game menu
        
        private int choice;                                 //User input
    
        
        /**
         * Displays the main menu and loads the next action based on user input.
         */
        public void mainMenu()
        {
            choice = mainMenu.display();
            
            switch(choice)
            {
                case 1: setUpMenu();
                        break;
                case 2: try{ loadSVG("SVG.txt"); }
                        catch(Exception e) 
                        { mainMenu(); }
                        break;
                case 3: System.exit(0);
                        break;
            }
        }
        
        /**
         * Displays the game set-up menu and loads the next action based on user input.
         */
        private void setUpMenu()
        {
            String p1Name = "", p2Name = "", word = "", me = "";
            boolean end = false;
            int diff = -1;
            
            choice = setUpMenu.display();
            
            switch(choice)
            {
                case 1: System.out.println("Enter player name that will guess a word: ");
                        p1Name = input.nextLine();
                        player1 = new Player(p1Name, true);
                        System.out.println("Enter next player's name: ");
                        p2Name = input.nextLine();
                        player2 = new Player(p2Name, false);
                        System.out.println("Enter the word to be guessed: ");
                        word = input.nextLine();
                        newGame(word);
                        gameMenu();
                        break;
                case 2: System.out.println("Enter your name: ");
                        me = input.nextLine();
                        player1 = new Player(me, true);
                        player2 = new Player("Computer", false);
                        System.out.println("Enter a difficulty (1-3): ");
                        while(!end)
                        {
                            diff = input.nextInt();
                            if(diff > 0 && diff <= 3)
                                end = true;
                        }
                        newGame(diff);
                        gameMenu();
                        break;
                case 3: System.out.println("Enter word for the computer to guess: ");
                        word = input.nextLine();
                        ai = new Solver(word);
                        ai.run();
                        break;
                case 4: mainMenu();
                        break;
            }
        }
        
        /**
         * Displays the in-game menu and loads the next action based on user input.
         */
        private void gameMenu()
        {
            String letter = "", word = "", answer = "", w2bg = "";
            boolean end = false;
            int diff = 0;
            
            gameMenu.clearScreen();
            
            player1.display();
            System.out.println();
            player2.display();
            man.displayBoard();
            choice = gameMenu.display();
            
            switch(choice)
            {
                case 1: while(!end)
                        {
                            letter = input.nextLine();
                            if(letter.length() == 1)
                                end = true;
                        }
                        if(man.isInWord())
                            man.addToCurrentWord();
                        else
                            man.addToGuesses();
                        man.displayBoard();
                        break;
                case 2: word = input.nextLine();
                        if(man.wordsMatch(word))
                        {
                            System.out.print("You Win!!");
                            if(player1.isGuesser())
                                player1.addToScore();
                            else
                                player2.addToScore();
                            
                            end = false;
                            while(!end)
                            {
                                System.out.println("Would you like to play again?(yes/no)");
                                answer = input.nextLine();
                                if(answer.compareToIgnoreCase("yes") == 0 || answer.compareToIgnoreCase("no") == 0)
                                    end = true;
                            }
                            
                            if(answer.compareToIgnoreCase("yes") == 0)
                            {
                                end = false;
                                if(player2.getName().equals("Computer"))
                                {
                                    System.out.print("Enter difficulty: ");
                                    while(!end)
                                    {
                                        diff = input.nextInt();
                                        if(diff > 0 && diff <= 3)
                                            end = true;
                                    }
                                    newGame(diff);
                                }
                                else
                                {
                                    System.out.print("Enter word to be guessed: ");
                                    w2bg = input.nextLine();
                                    newGame(w2bg);
                                }
                            }
                            else
                                mainMenu();
                        }
                        else
                        {
                            System.out.print("The word " + word + " is not correct.");
                            gameMenu.pressEnterToContinue();
                        }
                        man.displayBoard();
                        break;
                case 3: System.out.println("The word you couldn't guess is: " + man.getWord());
                        gameMenu.pressEnterToContinue();
                        gameMenu();
                        break;
                case 4: createSVG();
                        break;
                case 5: mainMenu();
                        break;
            }
        }
        
        /**
         * Saves the current game's data for later use.
         */
        private void createSVG()
        {
            final File parentDir = new File("Saved Game");      //Parent directory
            final String hash = "SVG";                          //Hash name for new file
            final String fileName = hash + ".txt";              //New file name and type
            Writer writer = null;                               //Used for writing to a file
    
            //Attempts to make the directory.
            try {
                String saveGameDir = "Saved Game";
                new File(saveGameDir).mkdir();
            }
            //Prints error if it can't
            catch(Exception e)
                { System.err.println("Error: " + e.getMessage()); }
    
            //Attempts to make new file
            try {
                final File file = new File(parentDir, fileName);
                file.createNewFile();
            }
            //Prints error if it can't
            catch(Exception e)
                { System.err.println("Error: " + e.getMessage()); }
    
            //Attempts to write the data to the file.
            try {
                writer = new BufferedWriter(new OutputStreamWriter(
                         new FileOutputStream(fileName), "utf-8"));
                writer.write(man.getWord());
                writer.write(man.getCurrentWord());
                writer.write(man.getGuesses());
                writer.write(man.getGuess());
                writer.write(man.getDifficulty());
            }
            //Prints error if it can't
            catch (IOException ex)
            {
                System.err.println("Error: " + ex.getMessage()); 
            }
            //Closes writer
            finally {
                try 
                    { writer.close(); }
                    
                catch(Exception ex) 
                    { System.err.println("Error: " + ex.getMessage()); }
            }
        }
    
        /**
         * Loads a saved game.
         * 
         * @param pathname      Path to file from current folder.
         */
        private void loadSVG(String pathname) throws IOException 
        {
            //loadSVG variables
            File file = new File(pathname);
            Scanner fromFile = new Scanner(file);
    
            //Variables for new SaveGame
            String word = "";
            String cWord = "";
            String guesses = "";
            String guess = "";
            int diff = -1;
    
            //Reads the file and saves it to a string
            try 
            {
                while(fromFile.hasNextLine() && diff == -1)
                {
                    word = fromFile.nextLine();
                    cWord = fromFile.nextLine();
                    guesses = fromFile.nextLine();
                    guess = fromFile.nextLine();
                    diff = fromFile.nextInt();
                }
            }
            //Closes scanner
            finally
            {
                fromFile.close();
            }
    
            //Creates a new SaveGame based on taken information
            SVG svg = new SVG(word, cWord, guesses, guess, diff);
    
            //Loads the saveGame
            man = new HangMan(svg);
        }
    
        /**
         * Starts a new game.
         * 
         * @param diff        Difficulty setting.
         */
        private void newGame(int diff)
        {
            man = new HangMan(diff);
        }
    
        /**
         * Starts a new game.
         * 
         * @param word        Predefined word.
         */
        private void newGame(String word)
        {
            man = new HangMan(word);
        }
    }

  2. #2
    Join Date
    Jun 2013
    Location
    New York, USA
    Posts
    21

    Resolved Re: Simple Yet Annoying Problem

    In your driver class, import JFrame and add the default close operation.

    Code:
    import javax.swing.JFrame;
    public class Driver
    {
        public static void main()
        {
            StartGame game = new StartGame();
            game.mainMenu();
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    Try that and see if it works.

  3. #3
    Join Date
    Jan 2011
    Location
    Orange County, CA
    Posts
    82

    Re: Simple Yet Annoying Problem

    Quote Originally Posted by Mercifies View Post
    Code:
    import javax.swing.JFrame;
    public class Driver
    {
        public static void main()
        {
            StartGame game = new StartGame();
            game.mainMenu();
            setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        }
    }
    I tried this out exactly how you put it (I am not familiar with JFrame) and I get an error saying that cannot find symbol- method setDefaultCloseOperation(int). So I'm looking into the JFrame class to see if I can find what you're doing exactly.

  4. #4
    Join Date
    Jun 2013
    Location
    New York, USA
    Posts
    21

    Re: Simple Yet Annoying Problem

    Sorry for the error yesterday, I forgot to extend JFrame. Do so by just adding it to the end of public class driver.
    Code:
    public class Driver extends JFrame {
    
    }

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured