-
Problem with Array
I am writing a program with arrays, the user is able to enter up to ten entries. The numbers get placed in the array, next the user is able to either search for a number in the array, or they can simply type in the index number and if its valid it would be displayed in a text field. I am able to do all of that, but all the numbers at index six and above are zero.
Code:
// ArrayAccess.java
import java.awt.*;
import java.util.*;
import javax.swing.*;
import java.awt.event.*;
public class ArrayAccess extends JFrame {
private JTextField inputField, retrieveValueField, retrieveIndexField, outputField;
private JPanel inputArea, inputPanel, retrievePanel, outputPanel;
private StringTokenizer splitter;
private int num, accessArray[];
private String input;
// set up GUI
public ArrayAccess()
{
super( "Accessing Array values" );
accessArray = new int[ 10 ];
// get content pane and set its layout
Container container = getContentPane();
container.setLayout( new FlowLayout() );
// set up input Panel
inputPanel = new JPanel();
inputPanel.add( new JLabel( "Enter array elements here" ) );
inputField = new JTextField( 10 );
inputField.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent e )
{
try
{
input = inputField.getText();
splitter = new StringTokenizer(input,",");
for(int x = 0; x <= splitter.countTokens(); x++)
{
accessArray[x] = Integer.parseInt(splitter.nextToken());
}
}
catch(Exception exc){System.out.println("Error");}
inputField.setText( "" );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
inputPanel.add( inputField );
container.add( inputPanel );
// set up retrieve Panel
retrievePanel = new JPanel( new GridLayout( 2, 2 ) );
retrievePanel.add( new JLabel( "Enter number to retrieve" ) );
retrieveValueField = new JTextField( 10 );
retrieveValueField.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
try
{
num = Integer.parseInt(retrieveValueField.getText());
for(int x = 0; x<accessArray.length;x++)
{
if(accessArray[x] == num)
{
outputField.setText("Number "+ num + " found at index: "+ x);
}
}
}
catch(NumberFormatException nfe){System.err.println("Bad Number Format");}
catch(NumberNotFoundException nnfe){System.err.println("Number Not Found");}
retrieveValueField.setText( "" );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
retrievePanel.add( retrieveValueField );
retrievePanel.add( new JLabel( "Enter index to retrieve" ) );
retrieveIndexField = new JTextField( 10 );
retrieveIndexField.addActionListener(
new ActionListener() {
public void actionPerformed( ActionEvent event )
{
try
{
num = Integer.parseInt(retrieveIndexField.getText());
outputField.setText("Number at index: " + num + " is "+ accessArray[num]);
}
catch(ArrayIndexOutOfBoundsException bounds){System.err.println("Bad index specified");}
catch(NumberFormatException number){System.err.println("Bad input");}
retrieveIndexField.setText( "" );
} // end method actionPerformed
} // end anonymous inner class
); // end call to addActionListener
retrievePanel.add( retrieveIndexField );
container.add( retrievePanel );
// set up output Panel
outputPanel = new JPanel();
outputPanel.add( new JLabel( "Result" ) );
outputField = new JTextField( 30 );
outputField.setEditable( false );
outputPanel.add( outputField );
container.add( outputPanel );
setSize( 400, 200 );
setVisible( true );
} // end constructor
// execute application
public static void main( String args[] )
{
ArrayAccess application = new ArrayAccess();
application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
}
} // end class ArrayAccess
Thanks for any suggestions
-
Might you be generating two tokens rather than one for each of your inputs? That would use up your allotment of 10 tokens with the first five inputs ...
Have you thought about using the Scanner class? It is easier and more direct to implement and has a pretty nextInt() method which will save some more effort with type checking ...
-
Do you have debugging ability with your IDE?
If not then I suggest that you add println() statements to your code that will show you what it is doing.
For example what is the values of splitter.countTokens() and splitter.nextToken()?
Separate composite statements into single, simple statements so you can see the values of variables:
Integer.parseInt(splitter.nextToken());
vs
String temp = splitter.nextToken();
System.out.println("temp= " + temp);
Integer.parseInt(temp);
-
I am using 1.4.2 and can't use the scanner class. I used a bunch of print statements ( like norm sugested) to get the values at different times and noticed that the bug is caused by the StringTokenizer. Does anyone know anything I can use instead of StringTokenizer ?
-
your problem is related with ActionListener.
becos actionPerformed never called for TextField in code, i dont know what is the "meaningful action" for that component too.
i simply put a FocusListener and it worked.
inputField.addFocusListener(
new FocusListener() {
public void focusGained(FocusEvent e ){}
public void focusLost( FocusEvent e )
...
Last edited by mr1yh1; 10-12-2005 at 10:31 PM.
-
What is the source of the commas which your tokenizer is supposed to be using?
-
I simply pass the comma as an argument to the constructor
splitter = new StringTokenizer(input,",");
-
> bug is caused by the StringTokenizer
Why do you say that?
Write a short test program that uses StringTokenizer with the String that you are having trouble with. Have a loop that gets and displays the tokens returned:
StringTokenizer st = ...
while(st.hasMoreTokens()) {
System.out.println(">" + st.nextToken() + "<");
}
That will show you how StringTokenizer works.
-
So ... is the comma being counted as a token by the countTokens() method?
Are you running out of tokens? Are you retrieving the first five and then losing the rest, or are you using tokens 1, 3, 5, 7, 9 [or 2, 4, 6, 8, 10] and then you have moved through your count ...
Think about your retrieval mechanism for tokens from splitter. What kind of data structure is splitter using to store the tokens? What methods do you know which will give you control over the retrieval of objects from that data structure? What methods does StringTokenizer expose to you for retrieving tokens one by one? What method does StringTokenizer give you to send a message to you that it has run out of tokens ... a boolean message which can control your while loop for adding elements to your accessArray?
You are telling the spitter object to use commas as the token delimiter. Where are the commas coming from which are being used by splitter to delimit the tokens? Your input is asking for integers ... I cannot find where the commas come in.
Last edited by nspils; 10-13-2005 at 10:55 AM.
-
Sorry about not telling you about that, I simply type them in as 0,1,2,3,4,5,6,7,8,9 (I should have let you guys know about that before)
-
I solved the problem by switching the for loop
Before
Code:
for(int x = 0; x <= splitter.countTokens(); x++)
{
accessArray[x] = Integer.parseInt(splitter.nextToken());
}
After
Code:
for(int x = 0;splitter.hasMoreTokens(); x++)
{
accessArray[x] = Integer.parseInt(splitter.nextToken());
}
Similar Threads
-
Replies: 0
Last Post: 10-30-2002, 05:40 AM
-
Replies: 3
Last Post: 10-15-2002, 02:58 PM
-
By Adam Right in forum ASP.NET
Replies: 0
Last Post: 01-27-2002, 06:44 PM
-
By Jack in forum VB Classic
Replies: 2
Last Post: 09-02-2000, 07:04 PM
-
By Mike in forum VB Classic
Replies: 32
Last Post: 04-12-2000, 07:52 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
-
Forum Rules
|
Development Centers
-- Android Development Center
-- Cloud Development Project Center
-- HTML5 Development Center
-- Windows Mobile Development Center
|