aspose file tools*
The moose likes Beginning Java and the fly likes methods, instances and arrays - swimming in the ocean of java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "methods, instances and arrays - swimming in the ocean of java" Watch "methods, instances and arrays - swimming in the ocean of java" New topic
Author

methods, instances and arrays - swimming in the ocean of java

Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Hello all,
Nice community you have here.
I've got a question about something that has been keeping me busy for a day or too. I'm a beginner at java, and i'm not really good at explaining stuff with their names, because i dont know them, so please excuse me, and correct me if i'm wrong

My problem is:
My main class(which contains the "main" method), creates an instance of a smaller class. The smaller class has an Arraylist in it, and i .add() things in it from my main class. I also created a method which gets the .size() of the array, so the main class knows its size. So far so good. I know though that outside the {brackets} of the main method, the instance does not exist.

Problem is I want to have a .toString() method in my main class, which returns the size of the array, but i cant do that, because i cant call the size() method outside the main class's main method, simply because it doesnt exist.

I figured that i must use a variable outside the main method, and store the size while the main method is still "alive", and retrieve it later on in the toString method. I tried that and i get an error "non-static variable cannot be referenced from a static context"

I hope i didnt confuse you.
and i also hope somebody has a solution for me
thanks!
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Simply making that variable static would get you past this obstacle; but I'm leery of that approach, because it sounds like there are some bigger design issues here (likely to raise bigger obstacles later). If you post some code, we could probably help you sort things out.
[ March 01, 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
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
see if you can follow this
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Originally posted by Michael Dunn:
see if you can follow this


If i get it right this line
|
V
public static void printSize(java.util.ArrayList al)

makes the printSize method to look for the instance we created before?
Michael Dunn
Ranch Hand

Joined: Jun 09, 2003
Posts: 4632
>If i get it right this line
>public static void printSize(java.util.ArrayList al)
>makes the printSize method to look for the instance we created before?

it prints the size of the arraylist passed to it via the parameter 'al'.

in the example, a Student class was created (which is local the the main()
method), students were added, then a reference to the ArrayList of the Student
Class 'st.students' was passed to the method printSize()
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
oh well i tried it and it didnt work. It prints out something like

PronunciationDictionary@1ea2dfe
or
PronunciationDictionary@cac268

PronunciationDictionary is the name of my main class.
This is printed out with the method you gave me. each time i call the printSize() method i get a different printout, just like the ones above.
*sigh*
[ March 01, 2005: Message edited by: black-drop ]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Static fields and methods -- like main() and Michael's printSize() -- only mean that they can be accessed directly from the class. In other words, you don't need to create a Testing -- using new Testing() -- to use them.Since Michael's add() method is an instance (non-static) method on class Student, you must call the method using an instance of Student.What Michael's done with printList() is have it take the ArrayList that's in the Student class (or any other ArrayList). It has no knowledge of the Student created in main().

Typically you'd put the toString() method on the class containing the ArrayList itself rather than in the class holding the main() method. You've already done this with your add() and size() methods, but let me know if you need more details or an example.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Woops sorry i didnt mean to paste all that..
I omitted something though, i'll try it out again.thanks for the help.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by black-drop:
oh well i tried it and it didnt work. It prints out something like

PronunciationDictionary@1ea2dfe
or
PronunciationDictionary@cac268

PronunciationDictionary is the name of my main class.
That is the default behavior of toString() defined in Object. The hexadecimal (base 16) number after the "@" is a hash of the object's address. You don't need to understand what the hash means, just that it's not entirely useful for your current needs.

Put the toString() method in your other class (the one without the main() method) as I wrote in my previous post.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by black-drop:
Woops sorry i didnt mean to paste all that..
You can edit your posts using the pencil and paper icon above the individual post. Try to use it only to fix posts (formatting, wording, etc.) rather than ask new questions or delete questions that have been answered, otherwise the thread is impossibly difficult to follow.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Thanks for the tip dave
Err, i wouldnt mind not doing that in the toString of the main class, but i am doing a uni assignment, and i have got directions to do so...
I did manage to get it to work when the toString was called from the main class as you told me, but how will i make it work when it is called from a third class?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Hi Mr. Drop,

Welcome to JavaRanch!

A bit of business: you may not have read our naming policy on the way in. It requires that you use a full, real (sounding) first and last name for your display name -- no "handles." This is one of the things that keeps our community "nice." You can change your display name here.

Thanks!


[Jess in Action][AskingGoodQuestions]
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
There
Would that qualify as a valid name?
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Krit c.:
There
Would that qualify as a valid name?


Closer, but no initials, please. Thanks.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by black-drop:
I did manage to get it to work when the toString was called from the main class as you told me, but how will i make it work when it is called from a third class?
Simply have it call through the PronunciationDictionary class:I assume PronunciationDictionary has a static reference to whatever object it is that you're creating and the static toString() method.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Originally posted by Ernest Friedman-Hill:


Closer, but no initials, please. Thanks.


hmm but the naming policy sais "You can even use initials for the first name if you like." !!
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Originally posted by David Harkness:
I assume PronunciationDictionary has a static reference to whatever object it is that you're creating and the static toString() method.


I tried that, and i only get back those hash numbers that you said toString prints as a default function. my toString() code looks like michael dunn told me


It works fine when i call it from the main method



but it doesnt when i call it from another class



My code might look funny heh, i'm still learning.

And thanks for your patience
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Originally posted by Krit c.:

hmm but the naming policy sais "You can even use initials for the first name if you like." !!


Indeed. Which means that you can't use an initial for your last (second) name.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Originally posted by Ernest Friedman-Hill:


Indeed. Which means that you can't use an initial for your last (second) name.


*sigh*
there
sorry for not reading the policy in the first place, everybody knows that terms and conditions are boring, especially when you're in a hurry to subscribe to a forum for help!
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

Thank you. I know it seems like a hassle, but you will actually find that more people are willing to help you now that you sound like a real person!
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
I solved the problem by creating a static variable in my main class, as marc weber suggested.What's the difference of a static variable from an "ordinary" variable?
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Krit Christoforou:
What's the difference of a static variable from an "ordinary" variable?
Just like static methods, you don't need an instance of the class to access it. As well, static methods have access to static fields of the same class. Search this forum for "static instance method" and you should get some hits. It is discussed every couple of weeks.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
I have no idea what you're talking about hehehe!!

I will do the search.

Thanks a lot for the tips
I'll be posting again soon because the project i'm working on is quite advanced for me..
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Heh, I'm trying to be terse but not vague. I don't think I pulled it off, though.

In Java (and most programming languages) things are segregated into groups having different behavior and requirements. The most basic in Java is the distinction between types: primitive values (char, int, float, double, byte, etc.) and object references (pointers to a unique instance of a class, called simply objects). Every variable has a type which determines what values can be stored in it, and each one is either a primitive or an object reference.The type of an object reference is either a class or interface, but it makes little difference to the variable itself. You'll learn more about this later, but let me get to static and instance members.

Classes and interfaces declare members that determine what data they store and operations they perform. While classes and interfaces differ in what forms the members they declare can take, from now on I'll address only classes.

There are two forms of members: fields (variables) and methods. Fields hold data for a class and methods define behavior. Each member can have several different modifiers applied to them, and one of them is the keyword "static." If a member is declared without this keyword, it is an instance member.

Here's an example to make this a little more concrete.Instance members belong to each instance of the class that declares them. If you instantiate (create using "new" operator or other means) three Employee objects, each will have its own name and age. Those fields belong to the Employee instances. Yet all instances of the Employee class share a single variable "count" since it's static.

The output of the above program will beAs you can see on line 2, you must call instance methods like getName() using an object reference because it must know which instance will receive the method call. On line 2, notice that the static method getCount() is called using the class's name. Think of static members as belonging to the class itself rather than any individual instance of the class. In fact, you don't need to instantiate any objects to use a class's static members.

There are many nuances I haven't covered in a hope that I wouldn't make this more confusing. As you play with these concepts you'll get used to it and you can start to learn the more advanced concepts.

I find it helps me to generalize concepts as I have above. Variables are primitives or references; members are static or instance. When you learn the basic language classifications, learning the others becomes easier.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
I think i get it..I also read the java tutorial and its quite simple.

Now i have the problem you predicted David. The static variable just solved the problem temporarily. I need to be able to access the array i created from all methods in the main method in my main class.

Let me explain again how it works.
This is my main method in my main class


The orhography class creates a treeset/hashset/arraylist(havent made up my mind yet), and it store words inside it.

Now, the PronunciationDictionary class has other methods as well, that need to call methods of the instance of the treeset/hashset/arraylist created in the main method.
I'm trying to work around by making my variables static but there is always something not working. If i cant do it soon, i'll post more specific error messages so that you can help.
Thanks!
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
I don't know if my question has any meaning, but is there any way of making an array or a set static?

*UPDATE* done it!
[ March 05, 2005: Message edited by: Krit Christoforou ]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
For this exercise, using static variables will certainly work. However, in object oriented software, it's best to create objects that have instance members. Static members are like global variables in C and C++.

One way to do this here would be to make all of the members of main be non-static and then have your main() method simply create a PronunciationDictionary and call methods on it to do the work. This way all of the instance methods will have access to the instance members of PronunciationDictionary without making them static.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
That would be a great idea, but i'm following instructions because this is an assignment, therefore i cant..

I am really confused because i think what i've been working on for some days now is completely wrong. I need answers to many questions in order to understand what situation i'm in and what i must do to get out.

My first questions are:
How can i get something i previously stored from a treeset since it has no get() method?
Is the only solution an iterator or an enumerator?
Isnt there another way, like an array to retrieve a member using something like arrayMember[i].getName() for instance?

Thanks in advance.
kritonas
[ March 05, 2005: Message edited by: Krit Christoforou ]
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Originally posted by Krit Christoforou:
How can i get something i previously stored from a treeset since it has no get() method?
TreeMap implements the Map interface which defines get() and put() and other methods. Map of course extends Collection which defines size() and other methods.

Feel free to post more code with questions.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Well basically i am completely lost concerning my assignment.
Thanks for the fast response david, i'll try to study a bit about the stuff you told me in your last post, tomorrow, and i'll get back with further questions.
What i'm trying to understand is not really in the code, these are just little things i'm trying to understand.
The thing is that i cant quite translate the instructions to code, i.e i have to create a class to represent a pronunciation dictionary, and two other classes. The first will represent individual words and the second one their individual pronunciations.And i have to create some methods in them.
I have completed half of my assignment, and then i saw that something's not right with it.
My two classes that are supposed to represent individual words and pronunciations dont do so. They just have a treeset each, and the first treeset stores words, and the second one pronunciations.
So i guess this is not what i was asked for because this way the two classes do not represent individual words/phonemes.

I'm sure what i've said makes little sense, but that's what's the most difficult part, to explain the problem.
I'll try to work a bit harder tomorrow and come up with clearer questions.
Thanks again
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
You explanation makes great sense. From it I would say that the PronunciationDictionary class should manage the TreeSets or other collections. Those collections would hold instances of the classes that represent individual words and their pronunciations.

One critical piece of missing information is whether each word has one or multiple pronunciations. This will determine which collections you choose and whether it's a single collection or collections of collections.

Here's a simple example of using a Map to convert from an int to its associated English ordinal word. Note that this wouldn't be how I'd implement the ordinal conversion functionality, but it does illustrate how to use a Map.Given that you'll use a word to lookup its pronunciation(s), you'll likely want to use one of the Map collections. I'd recommend starting with the simpler Word and Pronunciation classes. Get those built and working, and then build the dictionary to manage them.

If you post the full text of the assignment, I'll try to explain it in other words that will help you understand how to turn it into code.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Originally posted by David Harkness:
You explanation makes great sense. From it I would say that the PronunciationDictionary class should manage the TreeSets or other collections. Those collections would hold instances of the classes that represent individual words and their pronunciations.


Well i know where to head to now.
My guess is that:
- I'll create two TreeSets in my main class.
- One of the sets will store words, and the other pronunciations.
- Each of the words will be represented by the smaller Orthography class, and each of the pronunciations will be represented by the similar Pronunciation class.
- Therefore each of the words will have the methods that are contained in those classes.

I'm not sure if i get it right, correct me if i dont. I am not considering the fact that i have duplicate words, at least not for now, until i understand how this works.

The thing that my brain refuses to think is how i will associate the two small classes with each member of the TreeSets. I.e how will the word "ANT",member of my words(orthography) TreeSet(which is in my main class), be associated with the Orthography class, and create an instance of the methods contained in the class?
I have done this again, but with an Array. I cant get my brain to think the same think, but with a TreeSet.
I wish i could reboot my brain

Cheers David, thanks a lot for your valuable help, right now you're my only source of information. And the boring java books, which don't actually help.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Your task is to design, write and test a java program which reads and stores a pronunciation dictionary in a form which is suitable for subsequent query operations. At this stage you will also produce some elementary query methods as specified below. You should use two classes – called Orthography and Pronunciation - to represent the spelling and pronunciation of individual words. Both should contain the following public methods:

contains Given a sequence of characters or phonemes as input, returns true if the orthography or pronunciation contains that sequence

startsWith Given a sequence of characters or phonemes as input, returns true if the orthography or pronunciation starts with that sequence

endsWith Given a sequence of characters or phonemes as input, returns true if the orthography or pronunciation ends with that sequence

isMinimalPair Given a word or its pronunciation as input, returns true if the orthography or pronunciation is a minimal pair i.e. it differs in at most one position

toString Produces a meaningful representation of the word or pronunciation

You will also require constructor methods and any accessors needed to support your design. You should also design a class called PronunciationDictionary to represent the dictionary. This class should have the following public methods:

contains Given a sequence of characters or phonemes as input, returns a set or sequence of words/pronunciations that contain that sequence

startsWith Given a sequence of characters or phonemes as input, returns a set or sequence of words/pronunciations that start with that sequence

endsWith Given a sequence of characters or phonemes as input, returns a set or sequence of words/pronunciations that end with that sequence

minimalPairs Given a word or its pronunciation as input, returns the set of words or pronunciations in the dictionary that differ from the word or pronunciation in at most one position

toString Produces a short description of the dictionary (eg number of entries)

You will also require one or more constructor methods and any other methods needed for your design (eg add). Think carefully about the object-oriented design of your classes. You may need other classes, but you must have the three specified above.

These are the instructions for the assignment, i was a bit reluctant in posting them since i'm using my real name and stuff, but i guess its ok, since you're just helping, and not giving me code or something.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Those instructions certainly leave a lot unspecified. Can words and pronunciations be treated as simple Strings? Is a phoneme a character? Are there multiple pronunciations per word? Those questions all have reasonable assumptions, but I'd recommend getting clarafication just to be sure.

My advice is still the same: get the Orthography and Pronunciation classes working in isolation, meaning do each separately and without regard to the PronunciationDictionary class. If the answer to my first question is yes, I don't see a difference between the two classes, but maybe I'm missing something.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Sorry - my mistake. The dictionary looks like this:

ABANDEDax b ae n d ih d
ABANDENax b ae n d eh n
ABANDONax b ae n d ax n

So its the words, some tabs and then the pronunciations.
I guess its ok to store them as strings. some of the words are the same, yes, but i'm not sure about the phonemes. There must be pronunciations that are the same as well, i'll look it up later because i have to go.
Oh yes, the pronunciations are made up from a set of 45 phonemes, separated by a space.
I will follow your instructions and start by making those classes work on their own firstly. The problem is that i'm confused as to how they'll work.
When i call contains ie on Orthography, and i say myString.Contains("Test") ,it should test if myString contains test?

Thanks
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
Right!
My Orthography and Pronunciation classes are fully functional now!
I guess i'll try to put PronunciationDictionary in the game, but with two arraylists, just to try and understand how it works, and then i'll experiment with sets/maps.
hope its not really hard.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Thanks, that makes things a bit less abstract now. It seems a word (Orthography) is really just a plain old String, though you should create an Orthography class that encapsulates that String and provides the methods in the instructions, like contains().
When i call contains ie on Orthography, and i say myString.Contains("Test") ,it should test if myString contains test?
Please elaborate on this a bit after reading my first paragraph. I think you understand, but I need a more detailed description -- better, code.

When it comes to the Pronunciation class, I don't think you can treat them as a String because I believe each phoneme should be treated as a character. For example, I suspect the Pronunciation.isMinimalPair(Pronunciation) method should return true for the phonemes for "abanden" and "abandon" even though they differ by two characters but only differ by one phoneme.

Of course, the instructions are confusing here because they say that it should take either an Orthography or Pronunciation. Is the goal really to compare words to pronunciations? I can't imagine that ever returning true. Or should you look up the pronunciation of a given word if you call the method on another pronunciation?If it's supposed to perform a lookup in the dictionary in order to compare words to words and pronunciations to pronunciations, then the isMinimalPair() methods will have to wait until the dictionary is complete. The other methods can be written without it, however.
[ March 07, 2005: Message edited by: David Harkness ]
marc weber
Sheriff

Joined: Aug 31, 2004
Posts: 11343

Originally posted by David Harkness:
For this exercise, using static variables will certainly work. However, in object oriented software, it's best to create objects that have instance members...

Absolutely!

Krit: Note that I mentioned the static option as a "crutch" to get past this obstacle. But I also tried to make it clear that this probably wasn't a good solution.
Krit Christoforou
Ranch Hand

Joined: Mar 01, 2005
Posts: 46
When it comes to the Pronunciation class, I don't think you can treat them as a String because I believe each phoneme should be treated as a character. For example, I suspect the Pronunciation.isMinimalPair(Pronunciation) method should return true for the phonemes for "abanden" and "abandon" even though they differ by two characters but only differ by one phoneme.


I thought of that.
I treat the phoneme sequence as a string, and when it comes to finding its minimal pair i use the tokenizer and split it up.
Here is my code for the isMinimalPair() of Pronunciation class.



you can guess what pron is, it's the pronunciation string.
David Harkness
Ranch Hand

Joined: Aug 07, 2003
Posts: 1646
Cool, looks like you're off to a good start. Let us know when you have questions.
 
 
subject: methods, instances and arrays - swimming in the ocean of java