Page 1 of 3 123 LastLast
Results 1 to 20 of 50
Like Tree2Likes

Thread: Getting more than one "return" from a method

  1. #1
    Mapisto is offline Senior Member
    Join Date
    Dec 2011
    Posts
    102
    Rep Power
    0

    Default 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

    Java 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? ) 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.

  2. #2
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default 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.

  3. #3
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default 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.

  4. #4
    Mapisto is offline Senior Member
    Join Date
    Dec 2011
    Posts
    102
    Rep Power
    0

    Default Re: Getting more than one "return" from a method

    Quote Originally Posted by pbrockway2 View Post
    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 :(

  5. #5
    kevinn205 is offline Member
    Join Date
    Nov 2011
    Posts
    65
    Rep Power
    0

    Default 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
    your on clas called load type

    system.out.println(math.numbElementsB);

  6. #6
    Mapisto is offline Senior Member
    Join Date
    Dec 2011
    Posts
    102
    Rep Power
    0

    Default Re: Getting more than one "return" from a method

    Quote Originally Posted by kevinn205 View Post
    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
    your on clas called load type

    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 View Post
    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.

    Thank you all, I really appriciate it!
    Last edited by Mapisto; 12-15-2011 at 01:34 AM.

  7. #7
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Getting more than one "return" from a method

    Quote Originally Posted by Mapisto View Post
    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)

    Java 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.

  8. #8
    kjkrum's Avatar
    kjkrum is offline Senior Member
    Join Date
    Apr 2011
    Location
    Tucson, AZ
    Posts
    1,060
    Rep Power
    6

    Default 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.
    Get in the habit of using standard Java naming conventions!

  9. #9
    Mapisto is offline Senior Member
    Join Date
    Dec 2011
    Posts
    102
    Rep Power
    0

    Default 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 :)

  10. #10
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default 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.

  11. #11
    Mapisto is offline Senior Member
    Join Date
    Dec 2011
    Posts
    102
    Rep Power
    0

    Default 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. #12
    2by4 is offline Banned
    Join Date
    Dec 2011
    Posts
    143
    Rep Power
    0

    Default Re: Getting more than one "return" from a method

    Quote Originally Posted by Mapisto View Post
    Hi,

    Java 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.
    Last edited by 2by4; 12-16-2011 at 01:01 AM.
    Mapisto likes this.

  13. #13
    Mapisto is offline Senior Member
    Join Date
    Dec 2011
    Posts
    102
    Rep Power
    0

    Default 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.

  14. #14
    Mapisto is offline Senior Member
    Join Date
    Dec 2011
    Posts
    102
    Rep Power
    0

    Default Re: Getting more than one "return" from a method

    Quote Originally Posted by 2by4 View Post
    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
    Last edited by Mapisto; 12-16-2011 at 01:25 AM.

  15. #15
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default 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.
    Mapisto likes this.

  16. #16
    Mapisto is offline Senior Member
    Join Date
    Dec 2011
    Posts
    102
    Rep Power
    0

    Default 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? : \

  17. #17
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Getting more than one "return" from a method

    would it take effect on the array in the main method? : \
    Try it and see!

  18. #18
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: Getting more than one "return" from a method

    Or try this one:

    Java 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;
    		}
    	}
    }

  19. #19
    2by4 is offline Banned
    Join Date
    Dec 2011
    Posts
    143
    Rep Power
    0

    Default Re: Getting more than one "return" from a method

    Quote Originally Posted by Mapisto View Post
    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.
    Last edited by 2by4; 12-16-2011 at 10:07 AM.

  20. #20
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    12,086
    Rep Power
    20

    Default 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:
    Java 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().

Page 1 of 3 123 LastLast

Similar Threads

  1. Replies: 3
    Last Post: 10-12-2010, 04:21 PM
  2. Replies: 1
    Last Post: 01-21-2010, 09:20 AM
  3. Replies: 3
    Last Post: 05-25-2009, 08:50 PM
  4. Replies: 2
    Last Post: 01-24-2009, 06:56 PM
  5. Replies: 1
    Last Post: 10-20-2008, 07:35 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •