aspose file tools*
The moose likes Beginning Java and the fly likes array confusion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Soft Skills this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "array confusion" Watch "array confusion" New topic
Author

array confusion

Mike Smith
Ranch Hand

Joined: Sep 23, 2005
Posts: 85
Good nite all,
I am somewhat stuck on an assignment problem;which will probably require me seeing the prof again. But, I though maybe I could try to solve as much as I could before seeing him; so it doesn't think I didn't give it my all. Anyways, the problem basically requires input to be read from the console, and each string then in turn needs to be given a reference into an array object. I have implemented a class which I will use in this program to manipulate the String and iterate through the string one character at a time. I know the following;
-I know I will need two loops since that is what the assignment suggest
-I will have to instantiate an Object of my class I previously implemented.
-For each object I will pass it the string from the input.
-I next have to find a way to display the string vertically instead of horizonatally.For example,
hello // read in from command line.

output.
h
e
l
l
o

I know I have to creat an array of my object MyString, then iterate through it to initialize it with the string input.
Then I have to print out the array elements(strings) in vertical positioning. I have the following code;

I have thought about this problem; and wrote out my game plan the best I know how to; but still a little confused to say the least.
IF I use the charAt(i) I can iterate through the string and then somehow print out the results, but I am still confused more so; on how to print out an array. I know I need another loop to print this out. But unsure of the basic make up. IF anyone could give me some suggestions; maybe this will click in my mind. Thanks again.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Mike Smith:
... I am still confused more so; on how to print out an array. I know I need another loop to print this out. But unsure of the basic make up...

You're very close with the lines you commented out...

Instead of "i < 30," just use "j < s.length."

The rest of it depends on how the MyString class is defined -- in particular, what methods are available for working with an instance of MyString.
[ November 06, 2005: Message edited by: marc weber ]

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer
sscce.org
Mike Smith
Ranch Hand

Joined: Sep 23, 2005
Posts: 85
Hello, well I got a few methods() in the class. Basically the purpose of the myString class is to iterate through a string one character at a time. I guess kind of like using a loop and the charAt() method on a string. However, I get a NullPointer exception still with this class when I test it. I know the problem has to do with method nomore(); in dereferencing the str variable I believe.
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by Mike Smith:
... I get a NullPointer exception still with this class when I test it. I know the problem has to do with method nomore(); in dereferencing the str variable I believe...

The MyString class could use some cleaning up, but it looks like it should function okay (within certain parameters). How exactly are you testing it?

With respect to the noMore() method, I would suggest two things:
  • First, you might want to turn this around to more() rather than noMore(). This will make it easier to use, becaue you can simply say "while there are more" rather than a double-negative "while it's not true that there are no more."
  • Second, within the method, you should incorporate greater-than or less-than testing instead of simple equals or not equals. Your current approach relies on incrementally testing each value. For example, if the Stirng length is 10, your're relying on hitting 10 before going into null territory: ...7, 8, 9, 10. But what if it's not incremental: ...7, 8, 15, 33...?
  • Campbell Ritchie
    Sheriff

    Joined: Oct 13, 2005
    Posts: 40034
        
      28
    Most beginners' books don't tell you there is a much simpler way to get a boolean return value than using if statements.
    Lst's say you want to return "true" of your int number "i" is equal to 3. Lost of people write this sort of thingbut all you actually have to write isYou can use the same sort of thing for your hasMore() method.
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Campbell makes a good point. Along similar lines (as part of the "clean up" I mentioned above), if you use an "if" statement to test for equality, then it follows that "else" implies not equal.

    [ November 07, 2005: Message edited by: marc weber ]
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hiya guys, thanks for the input. I tried that and it doesn't pass my test then. But that is okay; I am going to see my instructor regarding that problem.

    But I am still confused about arrays. I know that they are like a tray of cups; a cup being a variable. I read this in the heads up text. I understand that inorder to print out an array you need to use a loop. But in my case I am confused how to return the strings in a vertical fashion; but learning how to print them would be a start.
    For example, I wish to receive input from the console, return a string, then display it vertically.





    I am creating a reference (str) to MyString objects, which I defined in another class. Then I am creating an array to hold 30 of these MyString objects that will contain a string for each object that was inputed from the user. Next, I use a for loop to assign the string to each object or element in the array. My problem is how do I return these strings from the array to just print out normally; then to print vertically. Thanks again
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Originally posted by Mike Smith:
    ... My problem is how do I return these strings from the array to just print out normally; then to print vertically. Thanks again

    I think you see that to print horizontally ("normally"), all you need is a println statement with the String.

    To print vertically, you just use a sequence of println statements (one for each line). But on each of these lines, you're not printing the String -- you're printing a char from that String. And you already have a method in MyString that will give you these chars.
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Ok, I think I just put myself in an infinite loop. One that approaches infinity.

    Mark, did you simple mean to print the array contents; I put
    System.out.println(test);

    I guess this line has no bearing on the code then.
    String [] s = str[i];
    I thought since str[i] holds the string references. I could assign that to a new String array, in order to print out what the strings were.
    It is not funny, when this stuff just isn't clicking in my head. Is there any good sources to understand how to use arrays. I understand the concept of arrays; that they are real objects on the heap; but I am having trouble understanding how to use them. Can you or someone else point me somewhere how to learn about using arrays, or give example of cases of storing things into arrays then printing out the contents of arrays. Thanks again.
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Originally posted by Mike Smith:
    ...I guess this line has no bearing on the code then.
    String [] s = str[ i ];
    I thought since str[ i ] holds the string references. I could assign that to a new String array, in order to print out what the strings were.

    Be careful with your types. Here, str is an array of MyString objects, with str[ i ] being a particular instance of MyString. But an instance of MyString is not a String, and certainly not a String array, so the assignment won't work. Instead, MyString has a String. So perhaps you meant to get the String from that particular instance (i) of MyString. That is, String s = str[i.getString()];

    On the other hand, I don't think there's a need for this -- in fact, it seems to defeat the purpose of having a MyString class. MyString already has a nextChar method.

    Originally posted by Mike Smith:
    ... Can you or someone else point me somewhere how to learn about using arrays, or give example of cases of storing things into arrays then printing out the contents of arrays. Thanks again.

    Here's the Array section in the Java Tutorial...

    http://java.sun.com/docs/books/tutorial/java/data/arrays.html
    [ November 07, 2005: Message edited by: marc weber ]
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Originally posted by Mike Smith:
    ...while(test!=null || j < str.length) {...

    Take a look at this line, and reconsider whether you want to use || or &&.
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hi, thanks Mark for pointing that out. I want the loop to iterate if the string is not null and to keep iterating up to the end of the array. But now i get;
    C:\92.1903\assignment 3\vertical.java:27: cannot resolve symbol
    symbol : variable test
    location: class MyString
    System.out.println(MyString.test.nextChar());
    ^
    1 error

    Tool completed with exit code 1
    It is having a problem finding my method() named nextChar. The MyString class file is in the same folder. How do I specify to the complier where it is. I thought a reference to object. method() in object (would suffice).
    I added the following println call.
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Originally posted by Mike Smith:
    ...
    C:\92.1903\assignment 3\vertical.java:27: cannot resolve symbol
    symbol : variable test
    location: class MyString
    System.out.println(MyString.test.nextChar());
    ...

  • MyString is a class (not an instance/object).
  • test is an instance of String (not MyString).
  • nextChar is a method that needs to be called on an instance of MyString.
  • With this in mind, take another look at my post above that says, "Be careful with your types."

    Then take a look at the line you commented out above...

    //System.out.println(int[j].nextChar());

    You don't have an array called "int." But if this were str[j], then it would be referencing an instance of MyString.
    [ November 07, 2005: Message edited by: marc weber ]
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hello, thanks for the input. I have decided to switch my code after seeing the Prof.
    The new code is the following;

    As you probably guessed it I am still having problems with it. I will make another post and explain what I see is happening; then hopefully someone can correct me, so I can learn from it.
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hello, Okay in the above code I see the following;
    - I create a reference to an array of MyString objects.
    - I then create the array using the new keyword and assign the array to 30 slots, so that each string will be placed in a slot.
    -I next introduce a while loop that will create a new Mystring obect; with the present String passed to the object by use of the argument. ie) test in arguement list.
    - This I believe stores the string into the element referenced by str.
    -I then increament the index.
    -The system.out.println(); is just for testing purposes; not part of the actual code.
    -Next I set up another while loop to go through the array of MyString objects that contain a string. And read the first char of each string in the array in a sequential manner. I then printout the line.
    -Finally I want to repeat the above process for all the indexes of the longest string.
    I don't know why str[j].nextChar(); is printing out null. I thought it should print out what I entered in; in a vertical manner. Anyways, I am still trying to figure this out. IF anyone could help that would be great. I am sorry for dragging this on so long.
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hello, Okay in the above code I see the following;
    - I create a reference to an array of MyString objects.
    - I then create the array using the new keyword and assign the array to 30 slots, so that each string will be placed in a slot.
    -I next introduce a while loop that will create a new Mystring obect; with the present String passed to the object by use of the argument. ie) test in arguement list.
    - This I believe stores the string into the element referenced by str.
    -I then increament the index.
    -The system.out.println(); is just for testing purposes; not part of the actual code.
    -Next I set up another while loop to go through the array of MyString objects that contain a string. And read the first char of each string in the array in a sequential manner. I then printout the line.
    -Finally I want to repeat the above process for all the indexes of the longest string.
    I don't know why str[j].nextChar(); is printing out null. I thought it should print out what I entered in; in a vertical manner. Anyways, I am still trying to figure this out. IF anyone could help that would be great. I am sorry for dragging this on so long.
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    You're getting closer. But there are a few issues.

    First, here's where the nulls are coming from...


    Second, look at this line...

    str is an array, and it's already been instantiated, so it's not null. You want to test array element references -- not the array reference itself.

    (Adding to the confusion is that there are 2 different str variables. In the class vertical, str is declared as an array of MyString objects; but in the class MyString, str is declared as a String.)

    Third, look at this loop...

    Consider what happens here step by step: j starts at zero. We get the nextChar() from str[0]. j is incremented to 1. Then j is incremented again to 2. (Do you see why?) We get the nextChar from str[2]. (So all we got from str[0] is one char before moving on to str[2].) j is incremented to 3, and then again to 4. We get nextChar() from str[4]...
    [ November 07, 2005: Message edited by: marc weber ]
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hi again.
    Okay I am unsure why
    str[i] = new MyString(test);
    results in a null? Aren't I just putting each string into a new element in the str array? I am confused with this part of code still.
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Originally posted by Mike Smith:
    ... I am unsure why str[ i ] = new MyString(test); results in a null? ...

    That line is fine. It creates a new instance of MyString and assigns it to the MyString reference at index i of the array str.

    The problem is what happens next: You increment the index variable, and then try to print. So in the println, you're no longer indexing the reference you just assigned -- you're indexing the next one, which is still null.

    For example, suppose i = 0. You create a new instance of MyString and assign it to str[0]. Now if you call println(str[0]), you would be okay. But instead, you're incrementing i to 1, and then calling println(str[1]). But str[1] hasn't been assigned to anything yet.

    Does that make sense?
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hi Mark, that part makes sense. I should have been printing before incrementing bc that value was null, since it did not yet iterate through.
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hi again. Now I get the nullPointer exception. Is there a way to fix this. I've changed my code to address the difference between the str and s variables. SO that is no longer a confusion in the code between MyString and vertical classes.
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Originally posted by Mike Smith:
    ... Now I get the nullPointer exception. Is there a way to fix this...

    The error message should indicate the line number in your code that's generating the exception.
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hi again. I am sorry for posting soo many posts. But I am not getting it; I'll see if I can get a tutor, as I seem to need it. Anyways,
    the problem lies here; char ch = s[j].nextChar();
    I don't see how s is being dereferenced or not referencing an object at this point. I i put in println calls I can alter my test results? for example with the previous case of incementing before printing.
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hello, I know that s[j] is not null since I tested it. I noted this on a web site to test for null condition. I simply put the following;


    If s[j] is not all what else can be null? I also tested s[i], which isn't either null. I am stomped any suggestions?
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Hmmm... Can you post your complete, current code for MyString and Vertical? I'm guessing that these classes have changed since the above examples.

    (I'm trying to steer you in the right direction without just giving you the solution, so that's why this thread seems long.)
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hi, not a problem. I will post it.

    MyString.



    I think I found the problem; but can't fix it. I am getting i=i+1; is an unreachable statement. It was compiling fine before when I had the increament before the return ch. But I realized that is incorrect; bc it was increamenting before returning that value; resulting in the null statement. But now I get unreachable statement for i=i+1;
    marc weber
    Sheriff

    Joined: Aug 31, 2004
    Posts: 11343

    Originally posted by Mike Smith:
    ... I am getting i=i+1; is an unreachable statement. It was compiling fine before when I had the increament before the return ch...

    A return statement causes execution to exit the method, so any lines after it are not reachable. You can safely move the incrementation to before the return line, because you've already retrieved the char and assigned it to ch.

    In the vertical class...
  • The first loop (the "initialization" loop) should simply iterate through the array and create new instances of MyString for each array index.
  • The second loop (the "array iterator" loop) should iterate through the array and "process" each instance of MyString in that array.
  • The third loop (the "processing" loop) should println each char in the instance of MyString that's being processed.
  • One problem is that the second loop is nested within the first loop. So before the first loop can go through and initialize each index of the array, the second loop steps in before it should. Because the first loop isn't allowed to finish, a NullPointerException is generated. The solution is to move those other loops outside of the first loop, so that the first loop can create all the instances of MyString before anything else happens.

    Another problem is that your null testing is checking whether the array reference itself (s) is null, but it's not checking whether the MyString references within the array (s[j]) are null, and this is where the NullPointerException is being generated. The solution is to test "s[j] == null" instead of just "s == null".

    Another problem is that the third loop is iterating through the array in the same manner as the second loop. The third loop should not be iterating through the array (going through each instance of MyString). Instead, it should only be dealing with chars (given a particular instance of MyString). Hint: Your nextChar() method already takes care of the incrementation and returns a zero value when there are no more chars. So you could use something like: while(thisChar != 0) {...
    [ November 08, 2005: Message edited by: marc weber ]
    Mike Smith
    Ranch Hand

    Joined: Sep 23, 2005
    Posts: 85
    Hi Mark, Thanks for the input, it is much appreciated. I have finally resolved my problem with your help and my instructors help. Thank you again. As it turned out my code was wrong; since I had too many loops. This caused many problems.
     
    I agree. Here's the link: http://aspose.com/file-tools
     
    subject: array confusion