簡體   English   中英

標為“繼續”的標簽似乎無效

[英]Labelled “continue” doesn't seem to work

剛開始學習Java,我不明白我的代碼有什么問題。 PrimeIterator應該生成無限數量的質數(從3開始),但是當我打印輸出時,得到: 3、5、7、9、11、13、15等。

public class Prime {

    PrimeIterator iter = new PrimeIterator();

    private class PrimeIterator implements java.util.Iterator<Integer>
    {
        int numb = 1;

        public boolean hasNext() 
        {
            return true;
        }

        public Integer next() 
        {
            nextCandidate:
            do{
                numb += 2;
                int numbSqrt = (int)java.lang.Math.sqrt(numb);

                for (int i = 3; i <= numbSqrt; i = i+2)
                {
                    if (numb % i == 0)
                    {
                        continue nextCandidate;
                    }
                }
            }while(false);
            return numb;
        }

        public void remove() {}
    }

    void printPrimes()
    {
        System.out.print(2);
        while(iter.hasNext())
        {
            try 
            {
                Thread.sleep(500);
            } catch (InterruptedException e) 
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            System.out.print(", " + iter.next());   
        }
    }
}

我想在我的do-while循環中使用標記為“ continue”的語句。 但是我的直覺告訴我我使用不正確。

問題在於while(false)延續條件。 作為do while(false)語句,這意味着它永遠不會循環超過一次。 也就是說,當您嘗試將執行跳轉到帶標簽的語句時,由於不會驗證繼續條件( false ),因此不會再次在do while循環,即使您認為continue會再次使執行循環。

因此,每次執行next()方法時,它絕不會使numb增加次數超過一次。

我會做如下的事情:

nextCandidate:
do{
    numb += 2;
    int numbSqrt = (int)java.lang.Math.sqrt(numb);

    for (int i = 3; i <= numbSqrt; i = i+2)
    {
        if (numb % i == 0)
        {
            continue nextCandidate;
        }
    }
    break;

}while(true);

這是我看到的問題

  1. 您甚至都沒有打印輸出。

  2. (int)java.lang.Math.sqrt(5)最終將截斷為2 您應該將1加到平方根,因為如果您沒有足夠的迭代,這將是一個問題,但是如果您進行了過多的迭代,這將不是問題。

  3. 當您找到質數時, for循環將結束,而while(false)將終止do-while循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM