This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Pulling code out and making method with it instead Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Pulling code out and making method with it instead" Watch "Pulling code out and making method with it instead" New topic
Author

Pulling code out and making method with it instead

Josh Priest
Greenhorn

Joined: Jun 06, 2007
Posts: 10
I had to create a program that passes an (array, array.length, item) to a method so that I can find and remove the item.

Rather than make the problem too complicated I just completed it inside of main and decided to migrate it to a method later.

My question is this, I cannot make the array smaller, but I can have the method return a new smaller array if the item was found.

like this:

if (found = true)
return array1
else
return array2

Can I do it like this?

Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 30068
    
149

Yes. The other alternative is to have:



Either approach is fine.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Or
Garrett Rowe
Ranch Hand

Joined: Jan 17, 2006
Posts: 1296
Also, when you factor out a method, you should ensure that you only pass in the minimum amount of information required to get the job done. There is no reason to pass the array.length as a parameter to the method. that information is implicit in the array.


Some problems are so complex that you have to be highly intelligent and well informed just to be undecided about them. - Laurence J. Peter
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19649
    
  18

David Newton wrote:Or

Almost. The correct answer is: "return array1;".

Josh, there is an assignment in the if-statement. This assignment takes place before evaluating found. It will therefore always be true. Use "if (found == true)", or even better, "if (found)".


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
David Newton
Author
Rancher

Joined: Sep 29, 2008
Posts: 12617

Heh.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37907
    
  22
To add to what Rob said yesterday about (found = true), I would say never to use == true and == false.
 
Don't get me started about those stupid light bulbs.
 
subject: Pulling code out and making method with it instead
 
Similar Threads
Find smallest element in arraylist
Arrays
jComboBox
ClassCastException in Tag Library
Recursion