Quantcast
Channel: Programming Forums
Viewing all articles
Browse latest Browse all 51036

Simple question about arrays in methods.

$
0
0
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? ://>

Viewing all articles
Browse latest Browse all 51036

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>