perfect numbers

i'm trying to get this code to test if a number is a perfect number.

for example, six would be a perfect number because all its factors(1,2,3 ) add up to six.

but i'm getting an error message.

does anyone know what i need to change? thanks

class PerfectNumbers{

publicstaticvoid main(String[] args){

test(28);

test(26);

test(6);

}

staticvoid test(int num){

int elements = 0;

for(int y = 1; y <=num; y++)

if(num % y == 0) elements+=1;

int[] factors =newint[elements];

for(int y = 1; y <=num; y++){

int p = 0;

if(num % y == 0) factors[p++] = y;

}

for(int y = 0; y < factors.length; y++){

int sum = 0;

sum = sum + factors[y];

}

if(sum == num) System.out.println(num+"is a perfect number");

else System.out.println(num+"is not a perfect number");

}

}

symbol : variable sum

location: class PerfectNumbers

if(sum == num) System.out.println(num+ "is a perfect number");

^

1 error

[2158 byte] By [mark_8206a] at [2007-11-27 0:00:36]
# 1
sum is declared inside the loop, so it's not known outside of the loop.KajPs. Please don't remove the first part of the error messages when you post.
kajbja at 2007-7-11 15:50:53 > top of Java-index,Java Essentials,New To Java...
# 2
Even you know the for loop will run, you shouldn't declare the variable inside.Same applies in if-else statement, while loop.
rym82a at 2007-7-11 15:50:53 > top of Java-index,Java Essentials,New To Java...