2 Replies - 162 Views - Last Post: 27 February 2013 - 10:58 AM Rate Topic: -----

#1 Quietus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 03-June 12

Simple question about arrays in methods.

Posted 27 February 2013 - 10:46 AM

So I get how arrays work. I get how methods work. I don't seem to understand how you combine the two.

Say for example in this program I intend to get the sum of the elements in an array. I know it's possible with only one method but for learning's sake, lets say I'd use another method. So far I've got this:

import java.util.Random;

public class Main {
	public static void main(String args[]){
		
		Random Rand = new Random();
		
		int arNum[] = new int[10];
		int ctr=0;
		int Answer;
		
		for(ctr=0;ctr<10;ctr++){
			arNum[ctr] = ((Rand.nextInt(6)) + 1);
		}
		
		Answer = getSum(arNum[ctr]);
		
		
	}
	
	public static int getSum(int x[]){
		
		int count=0;
		int sum = 0;
		
		for(count=0;count<=x.length;count++){
			sum += x[count];
		}
		
		return sum;
	}
}




Now the error is here:

Answer = getSum(arNum[ctr]);



Why doesn't that work? ://>

Is This A Good Question/Topic? 0
  • +

Replies To: Simple question about arrays in methods.

#2 Quietus  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 3
  • Joined: 03-June 12

Re: Simple question about arrays in methods.

Posted 27 February 2013 - 10:53 AM

Ooooh. I found what went wrong. Apparently you should only type in:

Answer = getSum(arnum);




That was quick. :whistling:
Was This Post Helpful? 0
  • +
  • -

#3 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7625
  • View blog
  • Posts: 12,855
  • Joined: 19-March 11

Re: Simple question about arrays in methods.

Posted 27 February 2013 - 10:58 AM

That's right: arnum[ctr] is the int which is located at index ctr. arnum is the whole array.
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1