-1

I'm trying to print all from 6 to n but when i run the code it gives me all the numbers but not the right perfect numbers. For example when I enter 30 it prints out all numbers but it says only 6 and 7 are perfect numbers only 7 is not a perfect number and 28 is.

import java.util.Scanner;


public class PerfectN {

public static void main(String[] args) {


            Scanner scanner = new Scanner(System.in);
            System.out.println("Enter a number that is 6 or above: ");
            int n = scanner.nextInt();

            int sum = 0;

            if(n<6){
                System.out.println("Incorrect number.");
            }
            else
                for(int i = 6;i<=n;i++){
                    for(int j = 1; j<i; j++){
                        if(i%j==0)
                            sum += j;
                    }


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



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

            }
        }

}
user3247712
  • 37
  • 2
  • 3
  • 8
  • Factor out a function, like `boolean isPerfectNumber(int number)`. If you did so, the error you have won't be even possible. – 9000 Nov 07 '14 at 20:35

1 Answers1

3

You need to reset the sum variable to zero for each number you go through:

for (int i = 6; i <= n; i++) {
    int sum = 0;
    for (int j = 1; j < i; j++) {
M A
  • 71,713
  • 13
  • 134
  • 174
  • 2
    The part that frustrates me is that I should've known this. Anyway, I'm still a beginner I guess but thanks a lot for the help! – user3247712 Nov 07 '14 at 20:47
  • Using a debugger would easily let you detect such a bug :) – M A Nov 07 '14 at 20:49
  • @user3247712 those are the kind of errors you won't get rid of no matter how much experience you gain. Only thing is, with more experience you will suspect those kind of error more willingly, and acquire a set of tools in your mind to detect more of them by yourself. ;-) . – Gyro Gearloose Nov 07 '14 at 20:53