# Getting more than one "return" from a method

Show 40 post(s) from this thread on one page
Page 1 of 3 123 Last
• 12-15-2011, 01:13 AM
Mapisto
Getting more than one "return" from a method
Hi,

I've added a part of a program I've coded.
After breaking my head on the wall figuring out a way to achieve something, I'd like a tip to a solution :(think):

Code:

``` public static void main(String[] args) { //main method starts                         Scanner scan = new Scanner(System.in);                 int[] B = new int[1000];                 int numElementsB = 0;                 int input_num;                 int counter=0;                                 do        {                         System.out.print("\nPlease insert integer #"+(counter+1)+":");                         input_num = scan.nextInt();                                                 if (input_num>0) {                                                         printDigits(input_num);                                 B = seperateDigits(input_num , numElementsB, B );                                 numElementsB=B[numElementsB+1]; //check this out......................!!!                         }//if ends                         counter++;                                numElementsB++;                 }//do ends                 while (input_num > 0);                 numElementsB--; public static int[] seperateDigits (int input_num , int numElementsB, int[] B ) { //seperateDigits method starts                 int first_numElementB = numElementsB;//This int will be used for "orderDigits" method in order to determine from which element to start swapping                 while (input_num>0) {                         B[numElementsB] = input_num%10;                         input_num/=10;                         numElementsB++;                                }//while ends                 B[numElementsB+1]=numElementsB;//Using the first untouched element to store the number of elements used in B.                 B=orderDigits(B , numElementsB , first_numElementB);                 return (B);```
Well, it's pretty messy I believe so I really thank anyone who bothers reading this post :)

As you can see in line 17, I'm calling ( or invoking is the right term? :(think): ) the method seperateDigits down below.
seperateDigits is supposed to take an int and seperate its digits into elements of an int array.
The problem is that I need to get more than 1 integer from the user and so the loop has to repeat itself (until the user presses zero) - which means the array should keep its former elements and get new ones in the next slots.

That's why I need the method not only to return B[] every time, but also to return the number of the last element being used.

After searching the web and finding out there's no way to get 2 return values from a method.. i thought of ways to do it, like using the first unused element in B array to store that number of last element for the method to "know" where to begin putting numbers the next time it gets an int.
Just after writing it I realized it just won't work.. coz in line 17: numElementsB=B[numElementsB+1]; it doesn't get back the "numElementsB" from the method...

So.. after all this writing.. i need a way to get this "numElementsB" back from the method and not just the array :(

I know it's long so I really don't expect any1 to read all this, but if you do, I'd really appriciate it.
• 12-15-2011, 01:31 AM
Junky
Re: Getting more than one "return" from a method
A method can only return ONE thing. What you can do is each time you call the method store the array it returns somewhere such as a 2D array or a List.
• 12-15-2011, 01:41 AM
pbrockway2
Re: Getting more than one "return" from a method
Or you could have a variable that seperateDigits() uses to remember where it got up to.
• 12-15-2011, 01:58 AM
Mapisto
Re: Getting more than one "return" from a method
Quote:

Originally Posted by pbrockway2
Or you could have a variable that seperateDigits() uses to remember where it got up to.

I do, "numElementsB", but i can't get it back to the main method.
and i can't make the seperateDigits method to remember it every time i invoke it. everytime I do so, it gets a new one :(
• 12-15-2011, 02:04 AM
kevinn205
Re: Getting more than one "return" from a method
are you sure you need a return method?

you could use static variables that are public?

public static numbElementsB;
int numbElementsB = 5;

if its to a differnet class call it as the class its on

system.out.println(math.numbElementsB);
• 12-15-2011, 02:26 AM
Mapisto
Re: Getting more than one "return" from a method
Quote:

Originally Posted by kevinn205
are you sure you need a return method?

you could use static variables that are public?

public static numbElementsB;
int numbElementsB = 5;

if its to a differnet class call it as the class its on

system.out.println(math.numbElementsB);

Well,
I'm pretty new to java so I don't really know what all those means.. we haven't got in class to the part of "object oriented programming".. just the basics.. and even if i did, I'm not alowed to use something i haven't learened yet i'm afraid.

Quote:

Originally Posted by Junky
A method can only return ONE thing. What you can do is each time you call the method store the array it returns somewhere such as a 2D array or a List.

This sounds like a good idea.. 2D array must solve this! I've never tried 2D arrays before.. so i'm off to read about it.:frusty:

Thank you all, I really appriciate it! :)-:
• 12-15-2011, 02:34 AM
pbrockway2
Re: Getting more than one "return" from a method
Quote:

Originally Posted by Mapisto
I do, "numElementsB", but i can't get it back to the main method.
and i can't make the seperateDigits method to remember it every time i invoke it. everytime I do so, it gets a new one :(

Kevin is right (except I would make it private)

Code:

```private static int numElementsB; public static void main(String[] args) {     //etc```
The only place numElementsB would be accessed is in the seperateDigits() method.

-----

Or use a 2D array.
• 12-15-2011, 09:30 AM
kjkrum
Re: Getting more than one "return" from a method
You seem to have found a solution. But to answer your original question, there are a few ways you can simulate multiple return values. You can return an object that has multiple fields within it. Or you can pass an object as an argument to the method, which the method will then modify. You'll see the second pattern used in stream I/O a lot, with methods like int read(byte[] b). The read method reads bytes from somewhere and writes them into the byte array b, and the method's return value indicates how many bytes were written.
• 12-15-2011, 04:19 PM
Mapisto
Re: Getting more than one "return" from a method
After doing some thinking, I figured another way that worked best for me.
Since you've helped so much i wanted to tell you what i did eventually.

First I was gonna use the 2D array idea, and then i thought about it.. and all the memory it takes for it.. and got to a new solution.
instead of using the first UNTOUCHED array element, that got me through all this mess... I've used the first array element (B[0]) to store the value of the location of the program in the array. it worked awesome!

Tho I believe that the ideas above were much simpler, I wish i had the knowledge to use them.. they won't let me use stuff we haven't learned yet :(

Thanks again everyone! for ur help and patience :)
• 12-16-2011, 01:20 AM
pbrockway2
Re: Getting more than one "return" from a method
I'm glad you've found a solution.

I think in the Pascal language strings use a similar technique: they are arrays most of whose elements represent characters except for the first which represent the length of the string.
• 12-16-2011, 01:48 AM
Mapisto
Re: Getting more than one "return" from a method
I used to learn Pascal at school when i was 14 :|
Compared to Java.. Pascal was so much easier..
that's probably because I've never used it to program anything complex.. :)
• 12-16-2011, 01:52 AM
2by4
Re: Getting more than one "return" from a method
Quote:

Originally Posted by Mapisto
Hi,

Code:

```                                B = seperateDigits(input_num , numElementsB, B ); ... public static int[] seperateDigits (int input_num , int numElementsB, int[] B ) { //seperateDigits method starts         ...                 return (B);```

There is no need to return B from separateDigits(). B doesn't change. You don't need to reset it after the call. It references the same array. Only the elements of B change.

That means you can return the current index from separateDigits();

Perhaps, this is part of the problem:

B=orderDigits(B , numElementsB , first_numElementB);

What does this do? If it is sorting the array, it doesn't need to change B, just rearrange its elements.
• 12-16-2011, 02:19 AM
Mapisto
Re: Getting more than one "return" from a method
tnx for ur reply,

I'm not sure I understand ur meaning.
After getting B back with the new values in the elements i need to know where it stopped each time. the only way of knowing it is to store that number somewhere so the program can follow.
I'm aware the indexes of B doesn't change, but the values are, and i need to care not to get new values on the existing values and erase them.
You say there's another way to tell where i've last stopped in feeling the array ?

and the reason I've returned all array B everytime from the method is that every time I'm getting a new integer from the user that needs to be seperated+ordered+put in the elements of B.
• 12-16-2011, 02:22 AM
Mapisto
Re: Getting more than one "return" from a method
Quote:

Originally Posted by 2by4
Perhaps, this is part of the problem:

B=orderDigits(B , numElementsB , first_numElementB);

What does this do? If it is sorting the array, it doesn't need to change B, just rearrange its elements.

well, yes, it is a big part of the problem, for example:

user input 1: 123
user input 2: 456

then the array looks like this
[0][3][2][1][6][5][4]

and that's becoz of using the modulus to seperate the numbers of every int.. so in order to order them to their original order i'm invoking the order method

and everytime i need to know exactly where to chage their order, not just taking the whole array and change it.

here's the method:

public static int[] orderDigits (int[] B , int numElementsB, int first_numElementB) { //orderDigits method starts - swaps elements to their original order
int temp;
while (first_numElementB<numElementsB) {
temp=B[first_numElementB];
B[first_numElementB]=B[numElementsB];
B[numElementsB]=temp;
numElementsB--;
first_numElementB++;

}
return (B);

oh, and when i say "change order" i don't mean chaning the indexes.. i mean swapping the values between the elements
• 12-16-2011, 02:24 AM
pbrockway2
Re: Getting more than one "return" from a method
2x4's point (and I think it was made before somewhere in the thread) is worth thinking about because it gets at an important distinction between passing references in Java and passing things in real life.

In RL if you wanted to buy a pound of oranges you might hand over your shopping bag, the shopkeeper puts the oranges in and then returns the bag. In Java the shopkeeper gets a reference to the bag and you keep your own reference. There is no need for the shopkeeper to return anything because you have your own reference and when you next look inside the bag it references the oranges will be there.
• 12-16-2011, 02:32 AM
Mapisto
Re: Getting more than one "return" from a method
what u mean is that i should have used a void method that just changes the values in the elements?

would it take effect on the array in the main method? : \
• 12-16-2011, 02:46 AM
pbrockway2
Re: Getting more than one "return" from a method
Quote:

would it take effect on the array in the main method? : \
Try it and see!
• 12-16-2011, 02:50 AM
pbrockway2
Re: Getting more than one "return" from a method
Or try this one:

Code:

```import java.util.Arrays; public class Test {         public static void main(String[] args) {                 int[] arr = new int[6];                 System.out.println("Before void method: " + Arrays.toString(arr));                                 foo(arr);                 System.out.println("... and after: " + Arrays.toString(arr));         }                 private static void foo(int[] arr) {                 for(int ndx = 0; ndx < arr.length; ndx++) {                         arr[ndx] = 42;                 }         } }```
• 12-16-2011, 11:01 AM
2by4
Re: Getting more than one "return" from a method
Quote:

Originally Posted by Mapisto
what u mean is that i should have used a void method that just changes the values in the elements?

would it take effect on the array in the main method? : \

(Couldn't you move orderDigits() into the main method?)

Anyway, pbrockway2's bag of oranges example answers your question.

When a method is invoked, Java passes in arguments by reference. (Some languages use passing by copy, and that is when you have to ensure your references don't get out of sync)

Check out "passing method arguments by reference and passing by copy". It is a crucial concept to understand.

When you pass a reference to an object into a method, you are asking the method to manipulate the referenced object. You only need a return value if the method produces something new that cannot be accessed via the references you have passed in.

Arrays are objects and you can think of them conceptually as such.

IMPORTANT NOTE: PRIMITIVE TYPES IN JAVA ARE PASSED BY COPY. So if you pass in an int, for example, it won't affect the int in your calling method.
• 12-16-2011, 11:41 AM
Tolls
Re: Getting more than one "return" from a method
Actually, java uses pass by value (that's the term I think you're looking for).
Yes, in relation to objects it is a reference that is passed, it is still only the value, not the actual reference itself, which is why the following has no effect on the reference passed in:
Code:

```void someMethod(SomeClass sc) {     sc = new SomeClass(); } void someOtherMethod() {     SomeClass sc = new SomeClass();     someMethod(sc);     // HERE. }```
At the point HERE the sc reference in someOtherMethod() still refers to the original object, not the one created in someMethod(). If Java were pass by reference then it would refer to the one created in someMethod().
Show 40 post(s) from this thread on one page
Page 1 of 3 123 Last