简体   繁体   中英

Java deciphering UML diagram

在此处输入图片说明

I have to write a program which computes the prime factors of a number. I have the algorithm done already, I just don't see how to use the methods hasMoreFactors and nextFactor. Here's my algorithm inside the constructor

int i = 2;

while (num > 1)
{
    if (num % i == 0)
    {
      System.out.println(i); // test if algorithm works
      factor.add(i);        // adds factor to array list
    }
else
{
  i++;
} 

My hunch is that I have to use hasMoreFactors in the algorithm, so I would replace this:

if (num % i == 0)

with hasMoreFactors().

if (hasMoreFactors() == true)

What you have there is the iterator pattern. You are supplying an iteratable data type Factors . That means the client of your code will be passing it a number to get all the calculated factors and then will retrieve them.

The two methods you have questions about are not for you to use per-se ; they need not be used in the code calculating the factors. They are part of the interface the client uses to get those calculated numbers.

You do need to implement them which is another question. The primary hint given to you is that you need to keep track of the current index the user is at.

Taking a look at the Java Iterator interface may be of some help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM