Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am learning JAVA.

I have created an array inside a method and now I have to return(as return type ARRAY) that array to main method and another user-defined method and print the values of that array from the main method and the user-defined method accroding to requirement.

Till now I have completed to print the values of the array from another method.

Please have a look at my code.

How can I do that?

import java.io.*;
import java.util.*;
public class java1
{
	public void GetPoints()
	{
		Scanner input = new Scanner(System.in);

        //allow user  input;
        System.out.println("Please enter n points");
		int num = input.nextInt();
		
		int array[] = new int[num];
		
		for (int i = 0 ; i < array.length; i++ )
		{
           array[i] = input.nextInt();
        }		
		//return  array;
        printArray(array);
	}
	
	public void printArray(int arr[])
	{
        
		int n = arr.length;
		System.out.println("These are the numbers you have entered.");

        for (int i = 0; i < n;i=i+2) {
            System.out.print(arr[i] + " ");
			System.out.print("(X:"+arr[i] + " "+",Y:"+arr[i+1] + " "+")");			
        }
    }
	public static void main(String args[])
	{
		java1 test = new java1();
		test.GetPoints();
	}
}
Posted

1 solution

So just save the value that the GetPoints methoid returns, aand call printArray from your main method:
Java
int array[] = test.GetPoints();
printArray(array);
All you have to do is set the return type for the GetPoints method to an array of ints - at the moment it is void (i.e. it returns nothing) and return the array as in your comments.
 
Share this answer
 
Comments
nischalinn 1-Apr-13 3:43am    
Thanks for the quick answer.
OriginalGriff 1-Apr-13 3:50am    
You're welcome!
nischalinn 1-Apr-13 5:26am    
hello OrignialGriff: how could I get the return type of GetPoints() directly to printArray method??
OriginalGriff 1-Apr-13 5:29am    
printArray(test.GetPoints());
should do it.
nischalinn 1-Apr-13 5:53am    
Thanks for the solution.
Could you please provide me link for defining user-defined multi-dimensional arrays and asking for user input for the same.
Thank You!!!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900