添加一个数的因数

Add the factors of a number

public static void main(String[] args) {
  Scanner x = new Scanner(System.in);
  int n = 0;
  int g = 0;
  int term = 0;
  int temp = 0;
  int sum = 0;
  int factor = 1;
  System.out.print("Input N:");

  n = x.nextInt();
  g = n;
  if (n <= 0) {
    System.out.println("Please enter a positive integer");
    System.exit(0);
  }

  if (n > 0) {
    System.out.print("The factors are:");

    while (factor < n) {
      if (n % factor == 0) {
        System.out.print(factor + ",");
      }
      factor++;
    }
  }
}

如果我输入数字 8,因数为 1,2 和 4。我想要实现的是将 8 的因数 1,2 和 4 相加,结果为 7。

import java.util.Scanner;

public class Demo {
public static void main(String[] args)
{
    Scanner x=new Scanner(System.in);
    int n=0;int g=0; int term=0;int temp=0;
    int sum=0; int factor=1;
    System.out.print("Input N:");

    n=x.nextInt();
    g=n;
    int number = 0;
    if (n<=0)
    {
        System.out.println("Please enter a positive integer");
        System.exit(0);
    }

    if (n>0)
    {
        System.out.print("The factors are:");

        while (factor<n)
        {
            if (n%factor==0)
            {
                System.out.println(factor+",");
                number+=factor;
            }
            factor++;
        }
    }
    System.out.println("Sum = "+number);
}
}
import static java.lang.System.*;
import java.util.*;
import java.io.*;

public class Main
{
    public static void main(String[] args)
    {
        Scanner kb = new Scanner(in);
        out.print("Enter a number: ");
        int num = kb.nextInt();
        int sum = 0;
        int x = 1;
        for(x = 1; x <= num; x++){
        if (num % x == 0){
        sum = sum + x;
          } 
    }
        out.print(sum);
}
}