Results 1 to 14 of 14
  1. #1
    daemonlies is offline Member
    Join Date
    Mar 2012
    Posts
    10
    Rep Power
    0

    Default Program not executing array correctly

    I'm having issues with executing a program that I have written. The program simply gets a user to input values whereby trying to guess a random number. I get to finding the median and the middle number but the program won't calculate them both. I need to use a insertion sort to be able to execute the median, but for some reason the program wont even do middle and median.

    Could someone have a look at my code and what I'm doing wrong please! I only posted some of the code to try not to confuse people to much

    Java Code:
    import java.awt.*;
    import java.awt.event.*;
    import java.util.*;
    import javax.swing.*;
    
    public class GuessGame extends JFrame
    {
        Container container;
        int currentDistance;
        int guesses;
        int size;
        int inputGuess;
        int lastDistance;
        double median;
        int middleNumber;
        int positionIndex;
        int test [] = new int [ 15 ];
        private int [] sort; 
        private JButton newGame;
        private JLabel message;
        private JLabel prompt; 
        private JLabel numberInput;
        private JTextField guessInput;
        private int countGuess;
        private int randomNumber;
        
        
          
        public GuessGame()
        {
            super( "Play Guess A Number Game Version 2.1" );
            setLayout( new FlowLayout() );
            
            countGuess = 0;
                    
            prompt = new JLabel( "A random number between N and 100 has been"
                    + " selected." );
            numberInput = new JLabel( "Write your number and press enter key: ");
            
            guessInput = new JTextField( 5 );
            guessInput.addActionListener( new GuessHandler() );
            message = new JLabel( "The result will be shown here." );
            
            
            newGame = new JButton( "Start New Game" );
            newGame.addActionListener( new ActionListener()
            {
                @Override
                public void actionPerformed( ActionEvent event )
                {
                   
                    guessInput.setText("");
                    guessInput.setEditable(true);
                                    
                    generateNumber();
                          
                }
            });
        
            container = getContentPane();
            container.add( prompt);
            container.add( numberInput );
            container.add( guessInput );
            container.add( message );
            container.add( newGame );
        
            setSize( 380, 150 );
            setVisible( true );
        
            generateNumber();
            
        }
        
        private void generateNumber()
        {
             
            randomNumber = ( int ) ( Math.random() * 93 + 7 );
            System.out.println( randomNumber );
                
        }        
           
        public void processGuessedNumber( int usersGuess )
        {
            countGuess++;
            
            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();
                }
            }
        }
        public void findMiddleNumber()
        {
            middleNumber = test[( guesses / 2 )]; 
            
            calculateMedian();
        }
        
        public void calculateMedian()
        {
            System.out.println( "Before:" );
            System.out.println( sort ); // print unsorted array
    
            insertionSort();
            
            System.out.println( "After:" );
            System.out.println( sort ); //
            
            
            if (( size % 2 ) == 0 ) 
               // even
                median = ( sort[ size / 2 ] + sort[ size / 2 - 1 ]) / 2.0;
                     
            else 
                median = sort[ size / 2 ];
                
            findGuessedNumbers();
        }
        
        public void insertionSort()
        {
                   
            sort = new int[ size ];
            
            for ( int i = 0; i < size; i++)
                sort[ i ] = inputGuess;
        
            sort();
        }
        
        public void sort()
        {
            int insert;
            
            for( int next = 1; next < sort.length; next++)
            {
                insert = sort[ next ];
                
                int moveItem = next;
                
                while( moveItem > 0 && sort[ moveItem -1 ] > insert )
                {
                    sort[ moveItem ] = sort[ moveItem -1 ];
                    moveItem--;
                }
                sort[ moveItem ] = insert;
                
            }   
                    
        }
                
       public void findGuessedNumbers()
        {
            finalOutput();       
    
            
        }
        
        public void finalOutput()
        {
            JOptionPane.showMessageDialog( null,"Congratulations, your guess "
                + "is correct." + "\n\n1. Middle number from all guessed "
                + "numbers by the user is: " + middleNumber + "\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: " + positionIndex, 
                "Final Output", JOptionPane.PLAIN_MESSAGE );  
        
        }
        
        public static void main( String [] args )
        {
            GuessGame application = new GuessGame();
            
           
            
            application.setDefaultCloseOperation( EXIT_ON_CLOSE );
                       
        }        
        
        class GuessHandler implements ActionListener
        {
            @Override
            public void actionPerformed ( ActionEvent event )
            {
                inputGuess = Integer.parseInt( guessInput.getText() );
                test[guesses] = inputGuess; 
                processGuessedNumber( inputGuess );
                guesses++;
                
                       
               
            }
        }   
    }
    Last edited by daemonlies; 05-02-2012 at 03:07 AM.

  2. #2
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Program not executing array correctly


  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: Program not executing array correctly

    The posted code does not compile. There is no way to execute and test it.
    If you don't understand my response, don't ignore it, ask a question.

  4. #4
    daemonlies is offline Member
    Join Date
    Mar 2012
    Posts
    10
    Rep Power
    0

    Default Re: Program not executing array correctly

    hopefully this helps

  5. #5
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: Program not executing array correctly

    Please post the console from when you execute the program and add some comments to it describing what is wrong with the output and show what the output should be.

    To copy the contents of the command prompt window:
    Click on Icon in upper left corner
    Select Edit
    Select 'Select All' - The selection will show
    Click in upper left again
    Select Edit and click 'Copy'

    Paste here.
    If you don't understand my response, don't ignore it, ask a question.

  6. #6
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,455
    Rep Power
    20

    Default Re: Program not executing array correctly

    Quote Originally Posted by doWhile View Post
    I've removed the double post. daemonlies, don't use the browser's back button to edit your posts as that creates multiple submissions.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  7. #7
    daemonlies is offline Member
    Join Date
    Mar 2012
    Posts
    10
    Rep Power
    0

    Default Re: Program not executing array correctly

    What i want to happen when the inputs have been given to guess the random number is that ...

    16 is the random number chosen by the program, its just for my benefit.

    i want to print the array of unsorted numbers from the users guesses and find the middle element odd or even.

    then i need to sort that array in another method using an insertion sort and then find the median number of those numbers even or odd.

    Could you help!!


    run:
    16
    Before:
    null
    After:
    [I@ab7165
    Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
    at GuessGame.calculateMedian(GuessGame.java:148)
    at GuessGame.findMiddleNumber(GuessGame.java:132)
    at GuessGame.processGuessedNumber(GuessGame.java:124)
    at GuessGame$GuessHandler.actionPerformed(GuessGame.j ava:224)
    at javax.swing.JTextField.fireActionPerformed(JTextFi eld.java:508)
    at javax.swing.JTextField.postActionEvent(JTextField. java:721)
    at javax.swing.JTextField$NotifyAction.actionPerforme d(JTextField.java:836)
    at javax.swing.SwingUtilities.notifyAction(SwingUtili ties.java:1661)
    at javax.swing.JComponent.processKeyBinding(JComponen t.java:2879)
    at javax.swing.JComponent.processKeyBindings(JCompone nt.java:2926)
    at javax.swing.JComponent.processKeyEvent(JComponent. java:2842)
    at java.awt.Component.processEvent(Component.java:628 2)
    at java.awt.Container.processEvent(Container.java:222 9)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4861)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.KeyboardFocusManager.redispatchEvent(Keyb oardFocusManager.java:1908)
    at java.awt.DefaultKeyboardFocusManager.dispatchKeyEv ent(DefaultKeyboardFocusManager.java:752)
    at java.awt.DefaultKeyboardFocusManager.preDispatchKe yEvent(DefaultKeyboardFocusManager.java:1017)
    at java.awt.DefaultKeyboardFocusManager.typeAheadAsse rtions(DefaultKeyboardFocusManager.java:889)
    at java.awt.DefaultKeyboardFocusManager.dispatchEvent (DefaultKeyboardFocusManager.java:717)
    at java.awt.Component.dispatchEventImpl(Component.jav a:4731)
    at java.awt.Container.dispatchEventImpl(Container.jav a:2287)
    at java.awt.Window.dispatchEventImpl(Window.java:2713 )
    at java.awt.Component.dispatchEvent(Component.java:46 87)
    at java.awt.EventQueue.dispatchEventImpl(EventQueue.j ava:707)
    at java.awt.EventQueue.access$000(EventQueue.java:101 )
    at java.awt.EventQueue$3.run(EventQueue.java:666)
    at java.awt.EventQueue$3.run(EventQueue.java:664)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:87)
    at java.awt.EventQueue$4.run(EventQueue.java:680)
    at java.awt.EventQueue$4.run(EventQueue.java:678)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPri vilege(ProtectionDomain.java:76)
    at java.awt.EventQueue.dispatchEvent(EventQueue.java: 677)
    at java.awt.EventDispatchThread.pumpOneEventForFilter s(EventDispatchThread.java:211)
    at java.awt.EventDispatchThread.pumpEventsForFilter(E ventDispatchThread.java:128)
    at java.awt.EventDispatchThread.pumpEventsForHierarch y(EventDispatchThread.java:117)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:113)
    at java.awt.EventDispatchThread.pumpEvents(EventDispa tchThread.java:105)
    at java.awt.EventDispatchThread.run(EventDispatchThre ad.java:90)

  8. #8
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,455
    Rep Power
    20

    Default Re: Program not executing array correctly

    Quote Originally Posted by doWhile View Post
    Another cross post; the code posted here as a starting point was provided by another member there.
    java - Trying to get input from JTextfield and use in another method - Stack Overflow

    db

    Oh lookee, a double post on SO: http://stackoverflow.com/questions/1...ray-in-program
    Last edited by DarrylBurke; 05-02-2012 at 06:42 AM.
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  9. #9
    daemonlies is offline Member
    Join Date
    Mar 2012
    Posts
    10
    Rep Power
    0

    Default Re: Program not executing array correctly

    Im in need of help ... not criticism ... and its asking a different question thankyou

  10. #10
    doWhile is offline Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,641
    Rep Power
    7

    Default Re: Program not executing array correctly

    Quote Originally Posted by daemonlies View Post
    Im in need of help ... not criticism ... and its asking a different question thankyou
    The link to other posts is not criticism, it helps those trying to help - unpaid and in their spare time mind you - know about answers or discussions on the topic that have not been disclosed by you. Everyone's time is valuable, yours and ours - if we are all on the same page then things get done faster, and people don't spend their time rehashing the same question or providing answers to question that have already been answered.

  11. #11
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,455
    Rep Power
    20

    Default Re: Program not executing array correctly

    It also lets other members here know that when you said
    Quote Originally Posted by daemonlies View Post
    Could someone have a look at my code
    you weren't being honest about the fact that all of that wasn't your code.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  12. #12
    daemonlies is offline Member
    Join Date
    Mar 2012
    Posts
    10
    Rep Power
    0

    Default Re: Program not executing array correctly

    Well it is 'my' code and i understand that peoples time and effort are going into this sort of thing which i appreciate and so do many ... but i find that more time has been spent on reflecting what i should have not been doing, instead of helping someone that asked for help ...

  13. #13
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    17,816
    Rep Power
    25

    Default Re: Program not executing array correctly

    Your code is a mess. Too many global variables. You should pass and return values to methods vs using global variables. There are methods that only call another method. Why not call that method directly? Instead of calling a method that calls another method. Call both of the methods from the same location, one after the other.

    Try debugging the code by adding lots of printlns to print out the values of variables as the are given values and used by the code. You need to see what variable have values and when they have values.
    If you don't understand my response, don't ignore it, ask a question.

  14. #14
    daemonlies is offline Member
    Join Date
    Mar 2012
    Posts
    10
    Rep Power
    0

    Default Re: Program not executing array correctly

    Thanks for that Norm .. will look at my coding again and sort it out !!! thank you

Similar Threads

  1. Replies: 2
    Last Post: 12-28-2011, 10:15 AM
  2. Blackjack Program Not Calculating Totals Correctly
    By skaterboy987 in forum New To Java
    Replies: 1
    Last Post: 10-19-2011, 09:59 PM
  3. Why doesn't my program function correctly?
    By robertbob in forum New To Java
    Replies: 7
    Last Post: 05-06-2010, 02:03 AM
  4. If statement not executing correctly
    By gligor_kot in forum New To Java
    Replies: 5
    Last Post: 08-03-2009, 02:46 AM
  5. help-executing the program
    By j2vdk in forum New To Java
    Replies: 6
    Last Post: 08-30-2008, 10:18 PM

Posting Permissions

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