Page 1 of 2 12 LastLast
Results 1 to 20 of 23
  1. #1
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default help with arrays

    Hi everyone,
    I am using JOptionPane input method to ask the user to enter a word. I am doing this in a while loop, which ends when no word is entered into the window. What I am trying to do is store all the words entered into the window into an array. I am wondering if this is possible and if so how is it done.This is what I have so far.

    import javax.swing.JOptionPane;
    public class SentenceReverse
    {
    public static void main(String[] args)
    {
    String word;
    word = JOptionPane.showInputDialog(null, "Enter a word");
    int n = word.length();
    String firstWord = word;
    if (n > 0)
    {
    int amountOfWords = 0;
    while(n != 0)
    {
    String newWord = JOptionPane.showInputDialog(null, "Enter a word");
    n = newWord.length();
    amountOfWords++;
    }
    String myArray[] = new String[amountOfWords];

    //What do I do here to store Strings in myArray???

    }
    System.exit(0);
    }

    }

  2. #2
    doWhile is online now Moderator
    Join Date
    Jul 2010
    Location
    California
    Posts
    1,642
    Rep Power
    7

    Default Re: help with arrays

    If you know how many will be entered, use an array Arrays (The Java™ Tutorials > Learning the Java Language > Language Basics)

    If you don't know how many you need to store from the beginning, use a List (in particular an ArrayList): The List Interface (The Java™ Tutorials > Collections > Interfaces)

  3. #3
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default Re: help with arrays

    What I am trying to do is store all the words entered into the window into an array
    Yes, this can be done. When you learn how to use ArrayList that will be a better way.

    Create an array that is large enough to hold all the possible user input.
    Define an index variable you will use to index the element in the array where you want to put the next word.
    Assign the word to the array element indexed by the index variable.
    Increment the index variable to point to the next empty slot in the array.
    When you are done, the index variable will have a count of the number of words you put in the array.

  4. #4
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default Re: help with arrays

    I'll have a go at this and see how i get on. Thanks for reply

  5. #5
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default Re: help with arrays

    I haven't got to arrays yet and haven't the time to grasp the concept yet so i'm going to try another way of solving my problem. What I have done declared a String variable which is initialised after a word is entered into input window. This input window keeps asking the user to enter a word until no word is entered.
    I then need to display the words that were entered in an output window. This is where I am getting stuck. The word entered is stored in a pre-defined String variable, but when another word is entered i'm guessing this new word overwrites the previous word.
    Bearing in mind I don't know how many words will be entered, how can I store all the words entered in seperate variables.
    Thanks in advance.

  6. #6
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default Re: help with arrays

    I haven't got to arrays yet
    I do not think you will be able to solve this problem without using an array, except for the trivial case of 2 or 3 words. You will have to learn how to use an array.
    Go to this site and Find: array
    Trail: Learning the Java Language: Table of Contents (The Java™ Tutorials)

  7. #7
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default Re: help with arrays

    I have looked at this tutorial and I understand what is being explained in it. But it doesn't really help me with my problem. I have tried declaring an int variable which increments everytime the loop is entered. This gives me the amount of words that are entered. I then used this variable to set up my array e.g. myArray = new String[amountOfWords];
    where variable amountOfWords is an int variable. What i dont understand is how do I initialise the elements of the array.

  8. #8
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default Re: help with arrays

    how do I initialise the elements of the array.
    Use an assignment statement for each element of the array:
    theArray[theIndex] = theValueForThisElement;

    Change the value of theIndex to get to the other elements of the array.

    Go back and read what I said in post#3.

  9. #9
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default Re: help with arrays

    This is what i have come up with. Can you tell me if i am heading in the right direction. When i compile this, I get an error saying cannot find variable myArray at output message. Thanks again for trying to help.
    Java Code:
    import javax.swing.JOptionPane;	
    public class SentenceReverse			
    {
    	public static void main(String[] args)	
    	{
    		String word;
    		word = JOptionPane.showInputDialog(null, "Enter a word");
    		int n = word.length();
    		int total = 0;
    		int amountOfWords = 0;
    		
    		while(n != 0)
    		{
    			total = total + n;
    			String newWord = JOptionPane.showInputDialog(null, "Enter a word");
    			n = newWord.length();
    			amountOfWords++;
    			if (amountOfWords > 0)
    			{
    				String[] myArray;
    				myArray = new String[amountOfWords];
    				myArray[amountOfWords] = newWord;
    			}
    		}
    		
    		
    		JOptionPane.showMessageDialog(null, myArray);
    		System.exit(0);
    	}
    	
    }
    Last edited by Norm; 11-27-2011 at 10:21 PM. Reason: added code tags. Please edit this to see how

  10. #10
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default Re: help with arrays

    You have define myArray within an inner pair of {}s. That is its scope of definition. When the execution leaves that scope, the variable goes away.
    The variable is not known outside of those {}s.
    You need to define a variable at the same level of {} nesting as you want to use it.

  11. #11
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default Re: help with arrays

    myArray[amountOfWords] = newWord;//amountOfWords is an int variable incremented everytime a word is entered and newWord is a String entered into input window. Is this method of initiating elements of an array allowed?

  12. #12
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default Re: help with arrays

    What do you mean by allowed? Does the compiler give you an error?
    What you are doing looks a little like what I said in post #3

  13. #13
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default Re: help with arrays

    It compiles without errors. When I run the program it shuts down after I enter second word. "Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1"
    I'm not sure what this means.

  14. #14
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default Re: help with arrays

    .ArrayIndexOutOfBoundsException: 1"
    On the line where the error occurred(given in the message) the value of the index was out of bounds/past the end of the array. The array must have less than 2 elements (an index of 1 is for the second element)
    You need to be sure the index stays within the limits of the array.


    If you create an array with 1 element the max index is 0. Look at your code and see if that is what happened.
    Last edited by Norm; 11-27-2011 at 10:49 PM.

  15. #15
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default Re: help with arrays

    okay understood, I can see what the problem is. I just can't seem to fix it.
    Java Code:
    import javax.swing.JOptionPane;	
    public class SentenceReverse			
    {
    	public static void main(String[] args)	
    	{
    		String word;
    		word = JOptionPane.showInputDialog(null, "Enter a word");
    		int n = word.length();
    		int total = 0;
    		int amountOfWords = 0;
    		String newWord;
    		while(n != 0)
    		{
    			total = total + n;
    			newWord = JOptionPane.showInputDialog(null, "Enter a word");
    			n = newWord.length();
    			amountOfWords++;
    			
    			
    		}
    		String[] myArray;
    		myArray = new String[amountOfWords];
    		myArray[amountOfWords] = newWord;
    		
    		
    		JOptionPane.showMessageDialog(null, myArray);
    		System.exit(0);
    	}
    	
    }
    error:newWord may not of been initialised.
    I know this is because that variable is initialised within a different level of nesting but that cant change in order for the program to work. I've tried other ways and every time I run into problems it seems to be a catch 22 situation.
    Again thank you for your patience and replies
    Last edited by Norm; 11-27-2011 at 11:21 PM. Reason: added code tags

  16. #16
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default Re: help with arrays

    You have to create the array before you read in the words.
    Java Code:
    create array of some given length
    declare counter variable
    loop {
        get user to enter word
        if user input is an actual word {
            if array is full {
                increase size of array
            }
            add word to array
            increment counter
        } else {
            exit loop
        }
    }
    Your need to do something like this.

  17. #17
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default Re: help with arrays

    error:newWord may not of been initialised.
    Assign it any value when you define it, for example: "a value";

    I can see what the problem is
    Please explain.

    In post #3 I gave you one way to do it. Have you tried doing the way I suggested?
    Here it is, with numbers.
    1)Create an array that is large enough to hold all the possible user input.
    2)Define an index variable you will use to index the element in the array where you want to put the next word.
    Begin a loop to read in word and put in the array
    3)As you read the words in, Assign each word to the array element indexed by the index variable.
    4)Increment the index variable to point to the next empty slot in the array.
    end of loop

  18. #18
    ddonn is offline Member
    Join Date
    Nov 2011
    Posts
    18
    Rep Power
    0

    Default Re: help with arrays

    I done what you have said and it works. My only problem is I don't know how many words are to be entered and I was trying to use the end value of the amount of words entered as a declaration of the length of the array but i will go with what I have now.
    Just one final question, is there a way to display the array in reverse order?
    If the array is "my name is", can I return "is name me"?

  19. #19
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,789
    Rep Power
    7

    Default Re: help with arrays

    :headdesk:

    The array is needed to store the words. Your algorithm is counting the words and not storing them. Once that is done you create an array with a size equal to the count. Then how are you supposed to store the words in the array since you have thrown them away?

    Printing out the elements of an array is simple. Just reverse the order of a for loop. That is start at the last element and decrease the index instead of increasing it.

  20. #20
    Norm's Avatar
    Norm is online now Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,338
    Rep Power
    25

    Default Re: help with arrays

    You can use the index to get any elements in the array you want to see.
    The index can start at 0 and increase to the last element,
    or the index can start at the last element and decrement until the first element.

Page 1 of 2 12 LastLast

Similar Threads

  1. arrays and multidimensional arrays
    By belfast09 in forum New To Java
    Replies: 5
    Last Post: 06-14-2011, 01:28 PM
  2. store array of arrays in array of arrays
    By joost_m in forum New To Java
    Replies: 4
    Last Post: 04-19-2010, 10:32 AM
  3. Arrays.sort... why sorting all arrays in class?
    By innspiron in forum New To Java
    Replies: 6
    Last Post: 03-23-2010, 01:40 AM
  4. Arrays
    By TheRocket in forum New To Java
    Replies: 6
    Last Post: 12-10-2008, 06:00 PM
  5. Need help with 2D arrays...
    By rrsv2 in forum New To Java
    Replies: 3
    Last Post: 11-30-2008, 03:15 AM

Posting Permissions

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