我在尝试让 testperfect 方法输出的数组正确打印时遇到问题,我知道我需要更改我的打印语句,但不确定如何(此语句在最后一个方法 printFactors 中)我需要它来打印因子在数组 testperfect 中,但我不希望它打印 0。我必须使用一个数组,并且该数组的大小为 100。
import java.util.Scanner;
public class name_perfect
{
public static void main ( String args [] )
{
int gN;
int gP = getPerfect();
int [] array = new int[100];
boolean tP = testPerfect(gP, array);
printFactors(gP, array, tP);
//System.out.println(Arrays.toString(array));
}
public static int getNum() //asks for how many numbers to test
{
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 ) //Checks if numbers input are 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() //asks for 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 ) //tests the numbers that were input
{
//testPerfect(perfect, array);
int limit = perfect;
int index = 0;
for ( int i = 1; i < limit ; i++)
{
if ( perfect % i == 0)
{ array[i]=i;}
}
array[index] = perfect;
int sum = 0;
for ( int i = 1; i < limit; i++)
{
sum = sum + array[i];
}
if ( sum == perfect)
{
//Something has to change the array here.
return true;
}
else
{
return false;
}
}
public static void printFactors(int perfect, int [] array, boolean tP )
{
if ( tP == true)
{
System.out.println (perfect + ":" + (Arrays.toString(array)));
}
else
{
System.out.println (perfect + ":" + "NOT PERFECT");
}
}
}