1.11M Members

Method returning an Array

 
0
 

Hi all,

I have a method set to return an array of type integer but I would like to know how I would access the independent values in that returned array. My program does this:

User enters numbers seperated by spaces and the program computes such things like the average, sum, product and minimum and maximum of those numbers.

I used the "StringTokenizer" class to allow the user to enter the numbers all at once without having to press enter in between. The method mentioned looks like this:

// Method to break up the string and place it inside an array
	public static int[] breakUp(String myString)
	{
		StringTokenizer sT = new StringTokenizer(myString);
		
		// Get the tokens and store them in an array, performing the conversion along the way
		int length = sT.countTokens();
		int [] myArray = new int[length];
		
		for( int i = 0; i < myArray.length; i++ )
		{
			int currentValue = Integer.parseInt( sT.nextToken().trim() );
			myArray[i] = currentValue;
		}
		
		return myArray;
		// Used to check to see if the method places the tokens into the array correctly
		// printArray(myArray);
		
	}

The point of this method is to save space and code because I don't want to include the declaration of the "StringTokenizer" in every method but still want to access the array easily.

Additional Information:

i) User data entered as a String
ii) String broken up into tokens
iii) Convert tokens to integer
iv) Integer's placed in an array for easy manipulation - sometimes...

Cheers :D

 
0
 

Call the method:

int [] array = breakUp("some string");
array[0];
array[1];
array[2];
....
 
0
 
return myArray;
		// Used to check to see if the method places the tokens into the array correctly
		// printArray(myArray);

This is not just a check; the return value is the only result of the method. myArray is a local variable - when you return from the method that created it, the variable goes out of scope and the results of your calculation are lost, except for the reference to them that the method returns.
There is no way to access myArray outside of your breakUp() method, unless you save a copy of it in the manner javaAddict suggests.

To be very clear: the String "myString" will not be changed after this method is run, and none of the variables declared in the body of the method will exist when it's finished. This is the difference between local variables and class fields.

 
0
 

Call the method:

int [] array = breakUp("some string");
array[0];
array[1];
array[2];
....

Cheers for the quick reply javaaddict
So you basically assign the values to another array in order to manipulate them; simple and effective.

Thanks mate it works now fine. If your curious the code is:

// Method to find the minimum and maximum of the numbers entered
	public static void findLow_findHigh(String myString)
	{
		int [] array = breakUp(myString);
		
		// Variables need a default value in order to compare them
		int maximum = array[0];		int minimum = array[0];
		
		for( int i = 1; i < array.length; i++ )
		{
			// If the next value along is greater than the previous then it becomes the maximum
			if( array[i] > maximum )
			{
				maximum = array[i];
			} else if( array[i] < maximum)
				{
				minimum = array[i];
				}
				else {
				
				}
		}
		
		// Print the values to the screen
		System.out.println("\nLargest Number entered was: "+maximum+"\nSmallest Number entered was: "+minimum);
	}

Ciao

 
0
 

You might want to look at that code again. Line 15 seems a little dodgy to me. :)

 
0
 

You might want to look at that code again. Line 15 seems a little dodgy to me. :)

How is it dodgy? The code works fine :P

 
0
 

Does it? It looks to me like this sequence:

1, 2, 3, 4, 5

should go fine

and

5, 4, 3, 2, 1

should go fine

but

1, 2, 5, 3, 4

should end up with minimum == 4

(on the last loop, maximum == 5. 4<maximum, so minimum = 4.

The in sequence and reverse sequence cases work for the wrong reasons. In sequence, minimum and maximum go:
1,1 1,2 1,3 1,4 1,5 (because i is always >= to maximum - it's always == maximum, to be precise)

In reverse sequence, the two take these values:

5,5 5,4 5,3 5,2 5,1 (because i < maximum in each case - lucky you, the last value of i is the true minimum)


Methinks your testing may not have been very extensive. :)

 
0
 

As JavaAddict points out, it is the checking issue that makes Katana24's method does not work perfectly. Therefore, some code has to be modified as:

for( int i = 0; i < myArray.length; i++ )
		{
			try {
			int currentValue = Integer.parseInt( sT.nextToken().trim() );
			myArray[i] = currentValue;
			}catch(NumberFormatException e){
				System.out.println("Non-digit character is involved. Input is not valid");
				return null;
			}
		}

In this way the method return null, implying the input string is not valid.

 
0
 

Sure, validation of input is always nice. But it'll work even betterer if the comparison in line 15 is to minimum, rather than to maximum.

 
0
 

Katana24 ,
the line 15 should be
} if( array < minimum)

You may consider how to deal with the situation where the input string includes both some digital tokens and some invalid tokens, e.g. "12g3".
How do you collect the valid inputs only ?

 
0
 

“An array is a container object that holds a fixed number of values of a single type”. Unfortunately it’s true for some cases only.
http://download.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html
I would say: “An array is a container object that holds a fixed number of values either a single type or different types.” In other words, in the Java programming language arrays are objects, are dynamically created, and may be assigned to variables of different types .
http://java.sun.com/docs/books/jls/second_edition/html/arrays.doc.html
In present post, one receives input as an String array via main’s argument. The method int [] breakUp(String [] myArray) collects the integer inputs, and the method Object[] process(int a[]) receives an int array and returns the outputs including maximum, minimum, project, and average via an Object array. Therefore, in the main’s body there are two lines of code only:

for (Object n:process(breakUp(args)))
		System.out.println(n);

The usefulness of returning an array by a method is obvious. But why it does not become a common practice/often used in Java?

import java.util.*;

public class Tokenizer1 {

	public static int [] breakUp(String [] myArray){
		int n = myArray.length;
		int a[] = new int[n];
		int counter=0;
		for( int i = 0; i < n; i++ ) {
			try {
			int currentValue = Integer.parseInt(myArray[i]);
			a[counter++] = currentValue;
			}catch(NumberFormatException e){}
		}
		if (counter==n)
		return a;
		if (counter !=0){
			int aa[]= new int[counter];
			for (int i=0; i<counter;i++)
			aa[i]=a[i];
			return aa;
		}
		return null;
		
	}
	
	public static Object[] process(int a[]) {
		int max=a[0];
		int min=a[0];
		int sum=a[0];
		int product=a[0];
		for (int i=1;i<a.length;i++){
			sum += a[i];
			product *=a[i];
			if(max<a[i])
			max=a[i];
			else if(min>a[i])
			min=a[i];
		}
		Object o[]=new Object[10];
		o[0]="Maximum: ";
		o[1]=max;
		o[2]="Minimum: ";
		o[3]=min;
		o[4]="Total: ";
		o[5]=sum;
		o[6]="Product";
		o[7]=product;
		o[8]="Average: ";
		o[9]=(double)sum/(double)a.length;
		return o;
	}
	
	public static void main(String args[]){
		for (Object n:process(breakUp(args)))
		System.out.println(n);
	}
	
}
You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article