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 + "." );
}
}