Hey everybody,

New to the java scene and having major issues, it would be appreciated if someone could have a look at my coding and see where i'm going wrong. I have a few

  1. When i press the 'start new game' button the random number resets but not the program doesn't, as it just comes up with an exception error after i enter an input.
  2. The program wont work out the median of a sorted array, i think because if the other values are zero that affects it .. what do i need to do to fix it ??
  3. I've tried to work out the postion of the random number once the array has been sorted .. i think maybe its the same as the median issue !!
  4. I need to work out how the user can only put values in ranging from 7 - 100, if outside those values than an error message and re-entering of an input must occur ... no idea !!
  5. I need to work out how to exit a program by entering ' -1 ' .. no idea

Could someone please have a look an help me out with my coding issues please

import java.awt.Container;   
import java.awt.FlowLayout;   
import java.awt.event.ActionEvent;   
import java.awt.event.ActionListener;   
import java.util.Arrays;   
import javax.swing.*;   

public class GuessGame extends JFrame   
{   
    Container container;   
    double median;    
    int guesses;    
    int inputGuess;    
    int middle;    
    int position;    
    int [] test = new int [ 10 ];    
    private JButton newGame;    
    private JLabel message;    
    private JLabel prompt;     
    private JLabel numberInput;     
    private JTextField guessInput;    
    private int countGuess;    
    private int randomNumber;     


    private void generateNumber()   
    {   

        randomNumber = ( int ) ( Math.random() * 93 + 7 );   
        System.out.println( randomNumber );   

        test = new int[ 10 ];   
    }           


    public void processGuessedNumber( int usersGuess )   
    {   
        int lastDistance;   
        int currentDistance;   

        //          
        countGuess++;   


        if ( usersGuess >= 7 && usersGuess <= 100 )          
        {    


        if ( countGuess == 1 )   
        {   
            lastDistance = Math.abs( usersGuess - randomNumber );   

            if ( usersGuess > randomNumber )   
                message.setText( "Higher than correst guess." );   

            else  
                message.setText( "Lower than correct guess." );   

        }   

        else    
        {   
            currentDistance = Math.abs( usersGuess - randomNumber );   

            if ( usersGuess > randomNumber )   
            {   
                message.setText( "Higher than correct guess." );   

                lastDistance = currentDistance;   

            }   

        else if ( usersGuess < randomNumber )   
        {   
            message.setText( "Lower than correct guess." );   

            lastDistance = currentDistance;   

        }   

            else  
            {   

                message.setText( "Congratulations, your guess is correct!" );   

                guessInput.setEditable( false );   
                countGuess = 0;   

                findMiddleNumber();   
            }   
        }   

        }   

        else    
        {   
            message.setText( " Invalid Guess - Numbers must be "  
                    + "between 7 - 100" );   

        }        

    }   

    //   
    public void findMiddleNumber()   
    {   


        if (( guesses % 2 ) == 0)   

            middle = test[(( guesses + 1) / 2 )];   

        else    

            middle = test[ guesses / 2 ];   

        System.out.println( Arrays.toString( test ));   

       sort();   
    }   

    public void calculateMedian()   
    {   



        System.out.println( Arrays.toString( test ));   


        if (( guesses % 2 ) == 0 )    

            median = test[ guesses ] / 2.0;   

        else    
            median = (test[ ((guesses + 1) / 2 )] + test[ guesses / 2]) / 2.0;   

        findGuessedNumbers();   
    }   

    public void sort()   
    {   
        int insert;   

        for( int next = 1; next < test.length; next++)   
        {   
            insert = test[ next ];   

            int moveItem = next;   

            while( moveItem > 0 && test[ moveItem -1 ] > insert )   
            {   
                test[ moveItem ] = test[ moveItem -1 ];   
                moveItem--;   
            }   
            test[ moveItem ] = insert;   

        }       

        calculateMedian();   
    }   
    public String toString()   
    {   
        return Arrays.toString( test );   


    }   

   public void findGuessedNumbers()   
    {   


        for ( int guesses = 0; guesses < test.length; guesses++ )   
        {   
            if (( test[ guesses ]) == randomNumber );   


             else  
                System.out.println( " " );   
        }          

        finalOutput();   


    } public GuessGame()   
    {   
        //   
        super( "Play Guess A Number Game Version 2.1" );   
        setLayout( new FlowLayout() );   


        //starts guesses count to 0   
        countGuess = 0;   


        //information for user to enter a number between 7 and 100   
        prompt = new JLabel( "A random number between 7 and 100 has been"  
                + " selected." );   

        //prompts the user to input a number and press enter   
        numberInput = new JLabel( "Write your number and press enter key: ");   

        //text field for user inputs   
        guessInput = new JTextField( 5 );   
        guessInput.addActionListener( new GuessHandler() );   

        //result of guessed numbers    
        message = new JLabel( "The result will be shown here." );   

        //button to start new game   
        newGame = new JButton( "Start New Game" );   
        newGame.addActionListener( new ActionListener()   
        {   
            @Override  
            //handle test event   
            public void actionPerformed( ActionEvent event )   
            {   
                //resets text field to null   
                guessInput.setText(" ");   
                guessInput.setEditable(true);   

                //generate random number method call   
                generateNumber();   


            }//end method actionPerformed   
        });   

        container = getContentPane(); //   
        container.add( prompt); //   
        container.add( numberInput ); //   
        container.add( guessInput ); //   
        container.add( message ); //   
        container.add( newGame ); //   

        //sets frame size layout    
        setSize( 380, 150 );   
        setVisible( true );   

        //generate random number method call   
        generateNumber();   

    }   

    class GuessHandler implements ActionListener   
    {   
        @Override  
        public void actionPerformed ( ActionEvent event )   
        {   

            do  
            {   
                if ( inputGuess != randomNumber )   
                {   
                    inputGuess = Integer.parseInt( guessInput.getText() );   

                    test[guesses] = inputGuess;   
                    processGuessedNumber( inputGuess );   
                    guesses++;   
                }   

                else    
                    test[guesses] = inputGuess;   

                    if ( inputGuess != randomNumber )   
                    {   
                        break;   

                    }               
            }   

            while ( inputGuess != randomNumber );              

        }   

    }   

    public void finalOutput()   
    {   
        JOptionPane.showMessageDialog( null,"Congratulations, your guess "  
            + "is correct." + "\n\n1. Middle number from all guessed "  
            + "numbers by the user is: " + middle + "\n\r2. Median "  
            + " value of all guessed numbers by the user is: "    
            + median + "\n\r3. A position (array index) of correctly "  
            + "guessed number in sorted array is: " + position,    
            "Final Output", JOptionPane.PLAIN_MESSAGE );    

    }   

    public static void main( String [] args )   
    {   
        GuessGame guessGame = new GuessGame();   

        guessGame.setDefaultCloseOperation( EXIT_ON_CLOSE );   



    }   
}  

sort only the part of inputted numbers upto guess, median is the middle number, maybe you are calculating for average in your function? Allways use only part of array used, not rest of it. Better would be to use ArrayList, which would only contain the inputed values.

Edited 4 Years Ago by pyTony

it just comes up with an exception error

Please post the full text of the error message.

This article has been dead for over six months. Start a new discussion instead.