程序无法正确计算因子并输入数组

时间:2012-11-20 01:33:37

标签: java arrays methods factorization

我遇到了testPerfect方法的问题。我需要它来计算因子并将它们放入数组中,然后如果数字是否完美则返回布尔值truefalse。到目前为止,数组刚刚获得1,2,3 ... 5,6,7 ...输入的任何数字进行检查。有什么建议?

import java.util.Arrays;
import java.util.Scanner;

public class moo_Perfect
{
public static void main ( String args [] )
{
    int gN;
    int gP = getPerfect();
    int [] array = new int[100];
    boolean tP = testPerfect(gP, array);
    //int printFactors;
    System.out.println(Arrays.toString(array));
}


public static int getNum() //Get amount of numbers to check
{
Scanner input = new Scanner ( System.in );
System.out.print( "How many numbers would you like to test? " );
int count = input.nextInt();
int perfect = 1;
boolean vN = validateNum(count, perfect);
while(!vN)
{
    System.out.print (" How many numbers would you like to test? ");
    count = input.nextInt();
    vN = validateNum(count, perfect);
}
return count;
}   

public static boolean validateNum( int count, int perfect  ) //Check if number is valid
{
if (( count <= 0) || ( perfect <= 0))

{ 
    System.out.print( "Non-positive numbers are not allowed.\n");
}



else 
{
    return true;
}
return false;


}
public static int getPerfect() //Gets the numbers to test
{
Scanner input = new Scanner ( System.in );
int perfect = -1;
int count = getNum();
System.out.print("Please enter a perfect number: " );
perfect = input.nextInt();  
boolean vN = validateNum(perfect, count);
while (!vN) 
{
    System.out.print("Please enter a perfect number: ");
    perfect = input.nextInt();
    vN=validateNum(perfect, count);
}
return perfect;
}


public static boolean testPerfect( int perfect, int[] array )

{
//testPerfect(perfect, array);
int limit = perfect;
int index = 0;
for ( int i = 1; i <=limit; i++)
{
    array[index++] = i;
    perfect /= i;
}
array[index] = perfect;
int sum = 0;
for ( int i =0; i < array.length; i++)
{
    sum = sum + array[i];
}

if ( sum == perfect)
{
    int[] w = array;

    return true;        
}

else
{
    return false;
}


}

1 个答案:

答案 0 :(得分:0)

这是一个List的作业,而不是一个数组(因为你不知道数组应该在手前多长时间,List来处理这个问题)。在实例化整数列表(例如,factors)之后,您可以将第一个for循环的主体更改为

if (perfect % i == 0) factors.add(i)

即。 “只有当i分成perfect时,才会将array[i] = (perfect % i == 0) ? i : 0 添加到我们的因素列表中。”


编辑 :如果 使用数组,则可以执行此操作

i

仅当perfect除以0时,才会将perfect放入数组中,否则会{{1}}。因此,此数组中元素的总和将等于{{1}}的因子之和。