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
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++;
}
}
}
Re: Program not executing array correctly
Re: Program not executing array correctly
The posted code does not compile. There is no way to execute and test it.
Re: Program not executing array correctly
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.
Re: Program not executing array correctly
Quote:
Originally Posted by
doWhile
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
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)
Re: Program not executing array correctly
Quote:
Originally Posted by
doWhile
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
Re: Program not executing array correctly
Im in need of help ... not criticism ... and its asking a different question thankyou
Re: Program not executing array correctly
Quote:
Originally Posted by
daemonlies
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.
Re: Program not executing array correctly
It also lets other members here know that when you said
Quote:
Originally Posted by
daemonlies
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
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 ...
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.
Re: Program not executing array correctly
Thanks for that Norm .. will look at my coding again and sort it out !!! thank you