Guessing Game, StackOverflowError

  • (2 Pages)
  • +
  • 1
  • 2

29 Replies - 2127 Views - Last Post: 13 April 2011 - 03:31 AM Rate Topic: -----

#1 exose  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 03-March 11

Guessing Game, StackOverflowError

Posted 06 April 2011 - 04:08 AM

Hi,

my program is compiling but does not work, code:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
import java.io.*;



public class GUI extends JFrame{

    public String response;
    public int secretNumber;
    public int max_GUESSES = 6;
    public int guess;

	public String userName;
	public String password;
	public String userNameInput;
	public String passwordInput;
    public JButton button;
    public JTextField textField;
    public JLabel promptLabel;
    public JLabel resultLabel;
    public JLabel randomLabel;


    public GUI()
    {
    	setLayout(new FlowLayout());
    	promptLabel = new JLabel("Enter a random number 1-100");
    	add(promptLabel);

    	textField = new JTextField(5);
    	add(textField);

    	button = new JButton("Guess!");
    	add(button);

    	resultLabel = new JLabel("");
    	add(resultLabel);

    	randomLabel = new JLabel("");
    	add(randomLabel);

    	Event e = new Event();
    	button.addActionListener(e);

    }

    public static void main(String[] args) {

        GUI guessingGame = new GUI();
        guessingGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guessingGame.setVisible(true);
        guessingGame.setSize(400,400);
        guessingGame.setTitle("Random Number Guessing Game");
    }
}


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

public class Event extends GUI implements ActionListener
{
	Random randomGenerator;

	public void actionPerformed(ActionEvent e)
	{
		int loopCounter=0;
		secretNumber = randomGenerator.nextInt(100);
		guess = (int)(Double.parseDouble(textField.getText()));

		do
		{
			loopCounter++;

			if (guess == secretNumber)
			{
        		resultLabel.setText("you won the game");

        	}
        	else if (guess < secretNumber)
        	{
        		resultLabel.setText("your number is lower, please guess again");
        	}

			else if (guess > secretNumber)
        	{
				resultLabel.setText("your number is higher, please guess again");
        	}
		}
		//while loop:
		while ((loopCounter < max_GUESSES)&&(guess != secretNumber));
		{
			resultLabel.setText("you had too many tries, please start game again");
			randomLabel.setText("the random number is "+ secretNumber);
		}
	}

}


Errors:

Exception in thread "main" java.lang.StackOverflowError
at javax.swing.text.StyleContext$SmallAttributeSet.equals(StyleContext.java:838)
at java.util.WeakHashMap.eq(WeakHashMap.java:259)
at java.util.WeakHashMap.get(WeakHashMap.java:353)
at java.util.Collections$SynchronizedMap.get(Collections.java:1975)
at javax.swing.text.StyleContext.getImmutableUniqueSet(StyleContext.java:503)
at javax.swing.text.StyleContext.addAttributes(StyleContext.java:323)
at javax.swing.text.AbstractDocument$AbstractElement.addAttributes(Abstractdocument.java:1971)
at javax.swing.text.AbstractDocument$AbstractElement.<init>(Abstractdocument.java:1762)
at javax.swing.text.AbstractDocument$LeafElement.<init>(Abstractdocument.java:2488)
at javax.swing.text.AbstractDocument$BidiElement.<init>(Abstractdocument.java:2660)
at javax.swing.text.Abstractdocument.<init>(Abstractdocument.java:132)
at javax.swing.text.Abstractdocument.<init>(Abstractdocument.java:92)
at javax.swing.text.Plaindocument.<init>(Plaindocument.java:74)
at javax.swing.text.Plaindocument.<init>(Plaindocument.java:64)
at javax.swing.text.DefaultEditorKit.createDefaultDocument(DefaultEditorKit.java:113)
at javax.swing.plaf.basic.BasicTextUI.installUI(BasicTextUI.java:785)
at javax.swing.JComponent.setUI(JComponent.java:662)
at javax.swing.text.JTextComponent.setUI(JTextComponent.java:322)
at javax.swing.text.JTextComponent.updateUI(JTextComponent.java:332)
at javax.swing.text.JTextComponent.<init>(JTextComponent.java:306)
at javax.swing.JTextField.<init>(JTextField.java:212)
at javax.swing.JTextField.<init>(JTextField.java:179)
at GUI.<init>(GUI.java:33)
at Event.<init>(Event.java:5)
at GUI.<init>(GUI.java:45)
at Event.<init>(Event.java:5)
at GUI.<init>(GUI.java:45)
at Event.<init>(Event.java:5)
at GUI.<init>(GUI.java:45)
at Event.<init>(Event.java:5)
at GUI.<init>(GUI.java:45)
at Event.<init>(Event.java:5)
at GUI.<init>(GUI.java:45)
at Event.<init>(Event.java:5)
at GUI.<init>(GUI.java:45)

do you have any idea what I did wrong? thanks for your input

Is This A Good Question/Topic? 0
  • +

Replies To: Guessing Game, StackOverflowError

#2 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 04:36 AM

Your Event is a subclass of GUI.
How do you create a new Event object in the GUI constructor?
what happens is that you recursively call the GUI constructor (since invoking Event's constructor, invokes the GUI constructor as well).
As you can see, it creates an infinite recursive call of the GUI constructor, which uses all the memory allocated by the your computer for that program. (StackOverflowError).
Was This Post Helpful? 2
  • +
  • -

#3 exose  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 03-March 11

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 06:00 AM

thank your input was really helpful, I have changed my code a bit to:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

public class GUI extends JFrame{

    //public String response;
    private int secretNumber;
    private int max_GUESSES = 6;
    private int guess;
    Random randomGenerator;

	//public String userName;
	//public String password;
	//public String userNameInput;
	//public String passwordInput;
    private JButton button;
    private JTextField textField;
    private JLabel promptLabel;
    private JLabel resultLabel;
    private JLabel randomLabel;


    public GUI()
    {
    	setLayout(new FlowLayout());
    	promptLabel = new JLabel("Enter a random number 1-100");
    	add(promptLabel);

    	textField = new JTextField(5);
    	add(textField);

    	button = new JButton("Guess!");
    	add(button);

    	resultLabel = new JLabel("");
    	add(resultLabel);

    	randomLabel = new JLabel("");
    	add(randomLabel);

    	Event e = new Event();
    	button.addActionListener(e);

    }

	public class Event implements ActionListener
	{

		public void actionPerformed(ActionEvent e)
		{
			int loopCounter=0;
			secretNumber = (randomGenerator.nextInt(100)+1);


			do
			{
				guess = (int)(Double.parseDouble(textField.getText()));
				loopCounter++;

				if (guess == secretNumber)
				{
	        		resultLabel.setText("you won the game");

	        	}
	        	else if (guess < secretNumber)
	        	{
	        		resultLabel.setText("your number is lower, please guess again");
	        	}

				else if (guess > secretNumber)
	        	{
					resultLabel.setText("your number is higher, please guess again");
	        	}
			}
			//while loop:
			while ((loopCounter < max_GUESSES)&&(guess != secretNumber));
			{
				resultLabel.setText("you had too many tries, please start game again");
				randomLabel.setText("the random number is "+ secretNumber);
			}
		}

	}

    public static void main(String[] args)
    {

        GUI guessingGame = new GUI();
        guessingGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guessingGame.setVisible(true);
        guessingGame.setSize(400,400);
        guessingGame.setTitle("Random Number Guessing Game");
    }
}


I am getting GUI displayed on my screen, but when I input a number I've got:

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at GUI$Event.actionPerformed(GUI.java:55)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:1995)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2318)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:387)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:242)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:236)
at java.awt.Component.processMouseEvent(Component.java:6267)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3267)
at java.awt.Component.processEvent(Component.java:6032)
at java.awt.Container.processEvent(Container.java:2041)
at java.awt.Component.dispatchEventImpl(Component.java:4630)
at java.awt.Container.dispatchEventImpl(Container.java:2099)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4577)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4238)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4168)
at java.awt.Container.dispatchEventImpl(Container.java:2085)
at java.awt.window.dispatchEventImpl(window.java:2478)
at java.awt.Component.dispatchEvent(Component.java:4460)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:599)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:269)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:184)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:174)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:169)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)
Was This Post Helpful? 0
  • +
  • -

#4 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 06:36 AM

Event e is declared ONLY in the constructor. so it is a local variable.
You have to declare it globally to let the class know it:

public class GUI.. {
  Event e;
  
  ...
  public GUI(){
    ...
    e = new Event();
    button.addActionListener(e);
  }
  ..
}

This post has been edited by japanir: 06 April 2011 - 06:36 AM

Was This Post Helpful? 2
  • +
  • -

#5 exose  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 03-March 11

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 06:53 AM

hmm not sure if I did that correctly as I am still getting the same error:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.Random;

public class GUI extends JFrame{

    //public String response;
    private int secretNumber;
    private int max_GUESSES = 6;
    private int guess;
    Random randomGenerator;

	//public String userName;
	//public String password;
	//public String userNameInput;
	//public String passwordInput;
    private JButton button;
    private JTextField textField;
    private JLabel infoLabel;
    private JLabel promptLabel;
    private JLabel resultLabel;
    private JLabel randomLabel;
    Event e;


    public GUI()
    {
    	JMenuBar menuBar = new JMenuBar();

        JMenu menuFile = new JMenu();
        JMenu menuSystem = new JMenu();
        JMenu menuSearch = new JMenu();

        JMenuItem menuFileExit = new JMenuItem();
        JMenuItem menuSystemLinear = new JMenuItem();
        JMenuItem menuSystemBinary = new JMenuItem();


		menuSystem.setText("Login");
		menuFile.setText("File");
		menuFileExit.setText("Exit");
		menuSystemLinear.setText("Linear");
		menuSystemBinary.setText("Binary");

    	infoLabel = new JLabel("Before you will be able to start the game you need to log in!");
    	add(infoLabel);

    	setLayout(new FlowLayout());
    	promptLabel = new JLabel("Enter a random number 1-100");
    	add(promptLabel);

    	textField = new JTextField(5);
    	add(textField);

    	button = new JButton("Guess!");
    	add(button);

    	resultLabel = new JLabel("");
    	add(resultLabel);

    	randomLabel = new JLabel("");
    	add(randomLabel);

    	e = new Event();
    	button.addActionListener(e);

    	// Add action listener.for the menu button
        menuFileExit.addActionListener
        (
            new ActionListener() {
                public void actionPerformed(ActionEvent e) {
                    GUI.this.windowClosed();
                }
            }
        );

        // Add action listener.for the linear search option
		menuSystemLinear.addActionListener
		(
			new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
						{
							GUI.this.linearLoginRequested();
						}
				}
		);

		menuSystemBinary.addActionListener
		(
			new ActionListener()
				{
					public void actionPerformed(ActionEvent e)
						{
							GUI.this.binaryLoginRequested();
						}
				}
		);

		menuFile.add(menuFileExit);
        menuBar.add(menuFile);
		menuSystem.add(menuSystemLinear);
		menuSystem.add(menuSystemBinary);
	 	menuBar.add(menuSystem);
	 	setJMenuBar(menuBar);

	 	// Add window listener.
        this.addWindowListener
        (
            new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    GUI.this.windowClosed();
                }
            }
        );

    }
    protected void windowClosed()
    {
        System.exit(0);
    }
	protected void linearLoginRequested()
	{
		String userName = JOptionPane.showInputDialog("Please Enter your Username:");
		String passWord = JOptionPane.showInputDialog("Please Enter your Password:");
	}
	protected void binaryLoginRequested()
	{
		String userName = JOptionPane.showInputDialog("Please Enter your Username:");
		String passWord = JOptionPane.showInputDialog("Please Enter your Password:");
	}
	public class Event implements ActionListener
	{

		public void actionPerformed(ActionEvent e)
		{
			int loopCounter=0;
			secretNumber = (randomGenerator.nextInt(100)+1);
			resultLabel.setText("you won the game"+secretNumber);

			do
			{
				guess = (int)(Double.parseDouble(textField.getText()));
				loopCounter++;

				if (guess == secretNumber)
				{
	        		resultLabel.setText("you won the game");

	        	}
	        	else if (guess < secretNumber)
	        	{
	        		resultLabel.setText("your number is lower, please guess again");
	        	}

				else if (guess > secretNumber)
	        	{
					resultLabel.setText("your number is higher, please guess again");
	        	}
			}
			//while loop:
			while ((loopCounter < max_GUESSES)&&(guess != secretNumber));
			{
				resultLabel.setText("you had too many tries, please start game again");
				randomLabel.setText("the random number is "+ secretNumber);
			}
		}

	}

    public static void main(String[] args)
    {

        GUI guessingGame = new GUI();
        guessingGame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        guessingGame.setVisible(true);
        guessingGame.setSize(400,400);
        guessingGame.setTitle("Random Number Guessing Game");

    }
}


Btw, I would like to disable my guessing button, and enable it when User will log in to the game by using correct credentials. I have found:

button.setMnemonic(KeyEvent.VK_D); and then button.setMnemonic(KeyEvent.VK_E); but I am not sure it this is what I am looking for?
Was This Post Helpful? 0
  • +
  • -

#6 m-e-g-a-z  Icon User is offline

  • Winning
  • member icon


Reputation: 495
  • View blog
  • Posts: 1,451
  • Joined: 19-October 09

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 08:11 AM

You have declared a Random here Random randomGenerator;but don't instantiate it thus causing a nullpointer exception since randomGenerator is pointing to null. You will have to instantiate randomGenerator in your GUI constructor.
Was This Post Helpful? 0
  • +
  • -

#7 exose  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 03-March 11

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 08:13 AM

generating secret number was wrong and it was 0, thats why that did not work...

the code now is:

public class Event implements ActionListener
	{

		public void actionPerformed(ActionEvent e)
		{
			int loopCounter=0;
			int max_GUESSES = 6;
			secretNumber = (int)(Math.random()*100+1);

			do
			{
				guess = (int)(Double.parseDouble(textField.getText()));

				if (guess == secretNumber)
				{
	        		resultLabel.setText("you won the game");

	        	}
	        	else if (guess < secretNumber)
	        	{
	        		resultLabel.setText("your number is lower, please guess again");
	        	}

				else if (guess > secretNumber)
	        	{
					resultLabel.setText("your number is higher, please guess again");
	        	}
	        	loopCounter++;
			}
			while ((loopCounter > max_GUESSES)&&(guess != secretNumber));
			{
				resultLabel.setText("you had too many tries, please start game again");
				randomLabel.setText("the random number was "+ secretNumber);
			}
		}

	}


But I still have a problem, while loop is working all the time and do loop does not work... do you know why? thanks for your time
Was This Post Helpful? 0
  • +
  • -

#8 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 9044
  • View blog
  • Posts: 33,550
  • Joined: 27-December 08

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 08:18 AM

You shouldn't be looping for input like you would in a console program. GUIs utilize Event-Driven Programming. Wait for the input. When the ActionEvent is fired, test to see if the user has guessed the maximum number of times. If so, tell them such. Otherwise, increment the counter and evaluate the input once. When the user submits again, the ActionEvent will be fired again and trigger the actionPerformed() method.
Was This Post Helpful? 2
  • +
  • -

#9 exose  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 03-March 11

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 08:57 AM

got that to work... :)

Anyway, do you know how I can disable button and enable it?

is there any specific piece of code for that?

This post has been edited by exose: 06 April 2011 - 09:08 AM

Was This Post Helpful? 0
  • +
  • -

#10 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 9044
  • View blog
  • Posts: 33,550
  • Joined: 27-December 08

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 09:02 AM

You declare count in your actionPerformed() method, so a new local variable is created each time the method is invoked. Make count an instance variable instead.
Was This Post Helpful? 3
  • +
  • -

#11 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 09:02 AM

have a global counter variable:
int counter = 0;

increase it's value by one in the actionPerformed method.
That will work since everytime the button is clicked the Event will be fired, and the actionPerformed method will be invoked.
Was This Post Helpful? 2
  • +
  • -

#12 macosxnerd101  Icon User is online

  • Self-Trained Economist
  • member icon




Reputation: 9044
  • View blog
  • Posts: 33,550
  • Joined: 27-December 08

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 09:04 AM

By "global", are you referring to instance fields? Generally, globals refer to static variables, which in general aren't good OO practice. :)
Was This Post Helpful? 3
  • +
  • -

#13 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 09:08 AM

Yeah, that is a bad phrasing..
By global variable I mean an instance field.
The reason I use the word 'global' is to show the difference between a variable declared locally in a method, to a variable declared as an instance field.
Was This Post Helpful? 2
  • +
  • -

#14 exose  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 29
  • Joined: 03-March 11

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 09:55 AM

View Postjapanir, on 06 April 2011 - 09:08 AM, said:

Yeah, that is a bad phrasing..
By global variable I mean an instance field.
The reason I use the word 'global' is to show the difference between a variable declared locally in a method, to a variable declared as an instance field.

got that to work... :) thank you very much ! :)

Anyway, do you know how I can disable button and enable it?

is there any specific piece of code for that?
Was This Post Helpful? 0
  • +
  • -

#15 japanir  Icon User is offline

  • jaVanir
  • member icon

Reputation: 1010
  • View blog
  • Posts: 3,025
  • Joined: 20-August 09

Re: Guessing Game, StackOverflowError

Posted 06 April 2011 - 10:09 AM

yeah,
setEnabled(true) or setEnabled(false):
http://download.orac...nts/button.html

API:
http://download.orac...nabled(boolean)
Was This Post Helpful? 1
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2