I am a beginner in Java and there are still several things I want to know as well as possibilities. I want to know if there is a way to "count" the amount of int after the out put. The objective of my simple code is to count the factors of the given number (example: factors of 10 are 1,2,5,10 and I should display "4" because it is the total amount of factors on the number). So far I can only display the individual factors (1,2,5,10 on example).

Here is my simple code.

public static void main(String[] args) {
  System.out.println("Enter a number whose factors are desired: ");

  Scanner scanNum = new Scanner(System.in);

  int numFac = 0;


  if(scanNum.hasNextInt())
  {
    numFac = scanNum.nextInt();
  }

  System.out.println("The Factors of the entered number are:-");

  for(int i = 1; i <= numFac; i++)
  {


    if(numFac%i == 0)
    {
      System.out.print(i+" ");
    }
  }
}

What are the possible things I can do?

有帮助吗?

解决方案

Introduce an int to count the factors.

int factorCount = 0;
for(int i = 1; i <= numFac; i++)
{  
    if(numFac%i == 0)
    {
       factorCount++;
       System.out.print(i+" ");
    }
}
System.out.println("Number of factors " + factorCount;

其他提示

So add counter:

int count = 0;
for(int i = 1; i <= numFac; i++) {
    if(numFac%i == 0) {
        System.out.print(i+" ");
        count++;
    }
}

System.out.print("Number of factors is: " + count);
 int displayFactors(int num) {
    int numOfFactors=0;
    for (int i = 1; i < num; i++) {
      if (num%i == 0) {
          numOfFactors++;
      }
    }
    return numOfFactors;
 }
public class Test {

public static void main(String[] args)
{
    ArrayList<Integer> x = numberFactors(5000);
    System.out.println("Factors: "+x+"\nTotal: "+x.size());
}

public static ArrayList<Integer> numberFactors(int num){
    ArrayList<Integer> aux=new ArrayList<>();
    for(int i=1;i<=num/2;i++){
        if((num%i)==0){
            aux.add(i);
        }
    }
    return aux;
}

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top