This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
The moose likes Java in General and the fly likes Java Guessing Game - OutOfMemoryError Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Java Guessing Game - OutOfMemoryError" Watch "Java Guessing Game - OutOfMemoryError" New topic
Author

Java Guessing Game - OutOfMemoryError

Cheryl Hill
Greenhorn

Joined: Apr 25, 2006
Posts: 2
Below are two java classes
This programming compiles just fine but when you run it you get an OutOfMemoryError. Can anyone tell me why this would be happening?


*Program window display

*/
//
import javax.swing.JFrame;

public class GuessLabel
{

public static void main( String args[] )
{
Guess guess = new Guess();
guess.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
guess.setSize( 250, 200 );
guess.setVisible( true );
}
}

=======================================================================
//Scanner Utility
import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.SwingConstants;


public class Guess extends JFrame
{
// Java Random Utility -
final int Num = new java.util.Random().nextInt(1001);
Scanner input = new Scanner( System.in);
int Guess;
int playagain;

private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JLabel label5;
private JLabel label6;
//private JLabel label7;
//private JLabel label8;
private JTextField inputJTextField;


private int previousDistance;
private int currentDistance;


public Guess()
{
super( "Kate's Guessing Game" );
setLayout( new FlowLayout() );

previousDistance = 0;
currentDistance = (Guess - Num );

label1 = new JLabel( "The computer has selected a random number between 1 and 1000. Go ahead, see if you can guess it!" );
add( label1 );


while ( true )
{
try
{
label2 = new JLabel( "Please enter your guess: " );
add( label2 );

JTextField inputJTextField = new JTextField( 12 );
add( inputJTextField );

// If the guess is less than 1, more than 1000, continue to the next guess
if (Guess >= 1 && Guess <= 1000)
break;
}

//Exception Handling- Only accept Integer values from 1-1000
catch ( NumberFormatException nfe )
{
label3 = new JLabel( "That must not be a number. Please enter an integer." );
add( label3 );
}
}

//If / Else Guess Results- Too high, or too low
if ( previousDistance != 0 )
{
if ( currentDistance == previousDistance )
inputJTextField.setBackground( Color.WHITE );

else if ( currentDistance < previousDistance )
inputJTextField.setBackground( Color.RED );

else
inputJTextField.setBackground( Color.BLUE );
}

if (Guess < Num)
label4 = new JLabel( Guess + " is too low. Try again!" );
add( label4 );

if (Guess > Num)
label5 = new JLabel( Guess + " is too high. Try again!" );
add( label5 );

if ( Guess != Num )
label6 = new JLabel( "Congratulations! The number was " + Num + "." );
add( label6 );




}
}
=========================================
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Looking at your code, you have an infinite loop and inside this loop, you keep calling the add method adding new instances of objects onto the frame until you run out of memory.

I assume you intended the user to input values? I don't see where you're changing Guess.
Kate King
Greenhorn

Joined: Apr 26, 2006
Posts: 8
I am not quite sure how this would be corrected. How would you eliminate the memory error, without eliminating the add method?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Insteading of adding the label to the frame each time, I would just add the label to the frame and call the setText method in the loop.
Kate King
Greenhorn

Joined: Apr 26, 2006
Posts: 8
Thanks for the help!

So, instead of

add( label2 );

You could
text.setText( label2 );

Would that be correct?
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Yeah. That should work. But also the code needs to be modified if you want user input.
Kate King
Greenhorn

Joined: Apr 26, 2006
Posts: 8
Is the input portion wrong as well??


label2 = new JLabel( "Please enter your guess: " );
add( label2 );
// Will this accept input?
JTextField inputJTextField = new JTextField( 12 );
add( inputJTextField );
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
Well you'll need to get the contents of the textfield with getText() in order to use them.
Kate King
Greenhorn

Joined: Apr 26, 2006
Posts: 8
Wow. I should have caught that. Thanks a million for all of the help. I have made some changes to my code, including your advive. I attempted to compile and run, however, I received a "NoSuchElement" error. So, I added exception handling code to handle the error, however, now I receive the NullPointerException, in line 97 and 13 in main. I am not quite sure how to correct this error.

Thanks!
~Kate


import javax.swing.JFrame;

public class GuessLabel
{

public static void main( String args[] )
{
Guess guess = new Guess();
guess.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
guess.setSize( 250, 200 );
guess.setVisible( true );
}
}
____________________________________________________________________________


import java.util.Scanner;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import java.awt.Color;
import javax.swing.SwingConstants;
import java.util.NoSuchElementException;


public class Guess extends JFrame
{
// Java Random Utility -
final int Num = new java.util.Random().nextInt(1001);
Scanner input = new Scanner( System.in);
int Guess;
int playagain;


private JLabel label1;
private JLabel label2;
private JLabel label3;
private JLabel label4;
private JLabel label5;
private JLabel label6;
private JTextField inputJTextField;



private int previousDistance;
private int currentDistance;


public Guess()
{
super( "Kate's Guessing Game" );
setLayout( new FlowLayout() );

previousDistance = 0;
currentDistance = (Guess - Num );

label1 = new JLabel( "The computer has selected a random number between 1 and 1000. Go ahead, see if you can guess it!" );
add( label1 );


while ( true )
{
try
{

label2 = new JLabel( "Please enter your guess: " );
add( label2 );
Guess = input.nextInt();
JTextField inputJTextField = new JTextField( 12 );
add( inputJTextField );

// If the guess is less than 1, more than 1000, continue to the next guess
if (Guess >= 1 && Guess <= 1000)
break;
}

//Exception Handling- Only accept Integer values from 1-1000
catch ( NumberFormatException nfe )
{
label3.setText( "That must not be a number. Please enter an integer." );

}
catch ( NoSuchElementException elementException )
{
System.err.println( "Invalid input. Please try again." );
input.nextLine();
}
}

//If / Else Guess Results- Too high, or too low
if ( previousDistance != 0 )
{
if ( currentDistance == previousDistance )
inputJTextField.setBackground( Color.WHITE );

else if ( currentDistance < previousDistance )
inputJTextField.setBackground( Color.RED );

else
inputJTextField.setBackground( Color.BLUE );
}

if (Guess < Num)
label4.setText( Guess + " is too low. Try again!" );


if (Guess > Num)
//Line 97 label5.setText( Guess + " is too high. Try again!" );


if ( Guess != Num )
label6.setText( "Congratulations! The number was " + Num + "." );


}
}
Cheryl Hill
Greenhorn

Joined: Apr 25, 2006
Posts: 2
Kate... have you gotten this to work yet? Please let me know if you do. I would love to have this code to play with.
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
You have to create the label before you do anything to it.

If I might offer a word of advice. I think it's going to prove pretty confusing if you mix your graphical input with console input. You are prompting the user inside the GUI, but you are expecting them to enter numbers at the command prompt. It will be easier for you and the user if you are consistent and just use the GUI. You could prompt the user to enter their value in the textfield and have a button on the GUI that they can click when they have finished.
Kate King
Greenhorn

Joined: Apr 26, 2006
Posts: 8
Thanks a million for all of your suggestions! This is really starting to make a little more sense to me!

I did add the text field and an action listener. I am now getting an error message in the last bracket of the Action Listener. I am not quite sure what to do. Your expert advice is greatly appreciated!

public class GuessLabel
{

public static void main( String args[] )
{
Guess guess = new Guess();
guess.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
guess.setSize( 250, 200 );
guess.setVisible( true );
}
}
___________________________________________________________________________

import java.util.Scanner;
import java.util.NoSuchElementException;
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;



public class Guess extends JFrame
{
// Java Random Utility -
final int Num = new java.util.Random().nextInt(1001);
Scanner input = new Scanner( System.in);

int Guess;
int playagain;

private JLabel instructionLabel;
private JTextArea instructions;
private Container contentPane;
private JTextField guessInput;
private int previousDistance;
private int currentDistance;




public Guess()
{
super( "Kate's Guessing Game" );

contentPane = getContentPane();
contentPane.setBackground( Color.WHITE );
contentPane.setLayout( new FlowLayout() );
setBackground( Color.WHITE );

previousDistance = 0;
currentDistance = (Guess - Num );

instructionLabel = new JLabel( "The computer has selected a random number between 1 and 1000. Go ahead, see if you can guess it!" );
add( instructionLabel );

guessInput.addActionListener(

new ActionListener() {

public void actionPerformed( ActionEvent event )
{
Guess = Integer.parseInt(guessInput.getText() );
}
}

while ( true )
{
try
{

instructions = new JTextArea( "Please enter your guess: " );
contentPane.add( instructions );

JTextField guessInput = new JTextField( 12 );
add( inputJTextField );

// If the guess is less than 1, more than 1000, continue to the next guess
if (Guess >= 1 && Guess <= 1000)
break;
}

//Exception Handling- Only accept Integer values from 1-1000
catch ( NumberFormatException nfe )
{
instructions.setText( "That must not be a number. Please enter an integer." );

}
catch ( NoSuchElementException elementException )
{
instructions.setText( "Invalid input. Please try again." );
input.nextLine();
}
}

//If / Else Guess Results- Too high, or too low
if ( previousDistance != 0 )
{
if ( currentDistance == previousDistance )
guessInput.setBackground( Color.WHITE );

else if ( currentDistance < previousDistance )
guessInput.setBackground( Color.RED );

else
inputJTextField.setBackground( Color.BLUE );
}

if (Guess < Num)
instructions.setText( Guess + " is too low. Try again!" );


if (Guess > Num)
instructions.setText( Guess + " is too high. Try again!" );


if ( Guess != Num )
instructions.setText( "Congratulations! The number was " + Num + "." );





}
}
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
You are declaring the anonymous class as the parameter to a method, but you have forgotten the parenthesis and semicolon.
Kate King
Greenhorn

Joined: Apr 26, 2006
Posts: 8
I guess, I would want to go ahead and remove the brackets at the end, so that the action listener incorporates the following inputs right?

guessInput.addActionListener(

new ActionListener() {

public void actionPerformed( ActionEvent event )
{
Guess = Integer.parseInt(guessInput.getText() );
} // remove?
} // remove?
Kate King
Greenhorn

Joined: Apr 26, 2006
Posts: 8
Sorry, I am not sure where you are referring to. Within the ActionListener?

Thanks!
Keith Lynn
Ranch Hand

Joined: Feb 07, 2005
Posts: 2367
No you don't want to remove the braces.

Notice that you are calling a method on guessInput but you aren't closing the call.

guessInput.addActionListener( <- This is the opening parenthesis.

new ActionListener() {

public void actionPerformed( ActionEvent event )
{
Guess = Integer.parseInt(guessInput.getText() );
} // remove?
} // remove?

But there is no closing parenthesis.
Kate King
Greenhorn

Joined: Apr 26, 2006
Posts: 8
Wow. Okay, I see.

If I don't remove the brackets, it won't incorporate the user's remaining guess input, will it?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Java Guessing Game - OutOfMemoryError
 
Similar Threads
why
jmenubar,menuitem
gui problems
ActionListener problem
Not able to read the value of a component on one JPanel from a different JPanel