> Java helpppppp Whats wrong with my code?

Java helpppppp Whats wrong with my code?

Posted at: 2014-12-18 
Corrected version of your code :

import java.util.Scanner;

public class PerfectNumbers

{

public static boolean isPerfect(int a)

{

int n = a;

int sum = 0;

boolean perfect;

while (n-- >1)

{if(a%n==0)

sum = sum + n;

}

if (sum==a)

{

perfect = true;

}

else

{

perfect = false;

}

return perfect;

}

public static void main(String[] args)

{

Scanner stdin = new Scanner(System.in);

System.out.println("Enter the number up to which you would like to look for perfect numbers:");

int i = stdin.nextInt();

String factors = "";

while (i>0)

{

if (PerfectNumbers.isPerfect(i)==true)

{int w = i-1;

while (w-- >1)

{if(i%w==0)

factors = factors + " " + Integer.toString(w);

}

System.out.println(i + " is a perfect number it's factors are: " + factors);

}

i = i-1;

}

}

}

I think you need to understand the difference between : if and while

and concept of variable scope

Thank you

All the best...

import java.util.Scanner;

public class PerfectNumbers

{

public static boolean isPerfect(int a)

{

int n = a-1;

int sum = 0;

boolean perfect;

while (a%n==0)

{

if (n!=1)

{

sum = sum + n + (a/n);

}

else

{

sum = sum + n;

}

}

sum++;

if (sum==a)

{

perfect = true;

}

else

{

perfect = false;

}

return perfect;

}

public static void main(String[] args)

{

Scanner stdin = new Scanner(System.in);

System.out.print("Enter the number up to which you would like to look for perfect numbers:");

int i = stdin.nextInt();

int w = i-1;

String factors = null;

while (i>0)

{

if (PerfectNumbers.isPerfect(i)==true)

{

while (i%w==0)

{

factors = factors + " " + Integer.toString(w);

w = w-1;

}

System.out.print(i + " is a perfect number it's factors are: " + factors);

}

i = i-1;

}

}

}

this was the goal:

An integer number is said to be a perfect number if its factors, including 1 (but not the number itself), sum to the number. For example, 6 is a perfect number, because 6 = 1 + 2 + 3.

Sample Output:

Enter the number up to which you would like to look for perfect numbers:Looking for perfect numbers from 1 to 1000

6 is a perfect number it's factors are: 1 2 3

28 is a perfect number it's factors are: 1 2 4 7 14

496 is a perfect number it's factors are: 1 2 4 8 16 31 62 124 248

Thanks in advance