Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Pulling code out and making method with it instead

 
Josh Priest
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
author & internet detective
Marshal
Posts: 34071
331
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes. The other alternative is to have:



Either approach is fine.
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Or
 
Garrett Rowe
Ranch Hand
Posts: 1296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Rob Spoor
Sheriff
Pie
Posts: 20492
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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)".
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Heh.
 
Campbell Ritchie
Sheriff
Posts: 48363
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
To add to what Rob said yesterday about (found = true), I would say never to use == true and == false.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic