• Post Reply Bookmark Topic Watch Topic
  • New Topic

Coding Your Own Classes(2)  RSS feed

 
Mark Do
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


1. What does the if-condition do?
If the name of a monster in the array is equal to the name stored in the variable, return the monster's assigned value.

2. What does the for loop do?
The loop condition simply loops through the whole arraylists. (In other words, it simply checks each Monster contained in the lists).

3. Assuming that the driver code compiles, explain what it’s use is?
If the name of the monster is the same as the variable passed unto this method, return the number assigned to that Monster.



I know that this is somewhat correct, but how do I answer the questions without trying to describe the code. I want my answers to be a bit more general than this. Thanks guys!

 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is a more object‑oriented way to do that. Give your Monster class an equals() method. Beware: equals methods are very difficult to write. Then you can pass a Monster you are looking for and the equals method will do that for you without having to look for the name.
If you go through the List interface, you will find it has a method already which probably does what you want.
 
Arthur Vinicius Rebelo
Ranch Hand
Posts: 30
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Assuming this :
I want my answers to be a bit more general than this.


I think this is a little more general :
1. What does the if-condition do?

Checks the equality from the current object compared to the object passed.

2. What does the for loop do?

Loops through the entire array

3.Assuming that the driver code compiles, explain what it is use is?

It's used to discover the index of an object if it's in the array.

And Campbell Ritchie is right, you should take a look at indexOf() method.
 
Mike. J. Thompson
Bartender
Posts: 689
17
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It's probably important to note that that codes finds the last index of the given object.
 
Arthur Vinicius Rebelo
Ranch Hand
Posts: 30
1
Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Nice noticed Mike J. Thompson
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't use <= if you can avoid it.
for (int i = 0; i <= myList.length() - 1; i++)… is much more difficult to read than the conventional format:
for (int i = 0; i < myList.length(); i++)…
Always use the conventional format, which people are familiar with. Also always use braces for if and while statements, etc.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!