JAVA:识别素数

时间:2014-11-25 06:37:21

标签: java

我写了一个代码来识别素数。没有语法错误,但是当它不是素数时,它再次循环以输入正整数。它应该是“再次尝试按1并退出按2”。

以下是我的代码:

import java.util.*;
public class TRY
{
 static Scanner Scan = new Scanner(System.in);
 public static void main (String[] arg)
{

   int n;

   System.out.println("Identify the if it's a prime number");

   while (true){

           System.out.println();
           System.out.println("Enter a positive integer:  ");
           n = Scan.nextInt();

        if (n>0)
           {
                   boolean isPrime = true;
                   for (int i = 2; i <= n/2;i++)
                   {
                    if (n % i == 0 ){
                                   isPrime = false;
                           }  
                   }
                   if (isPrime){
                           System.out.println("The integer you entered " + n + " is a PRIME NUMBER!");
                   }
                   else
                   {
                           System.out.println("The integer you entered " + n + " is not a PRIME NUMBER!");
                           continue;
                   }
                   System.out.println();
                   System.out.println("To try again press 1 and to exit press 2");

                   if (Scan.nextInt() == 1)
                   {
                           continue;
                   }
                   else
                   {
                           System.out.println("Thank you!");
                           break;
                   }


     }
  }
}
}

1 个答案:

答案 0 :(得分:1)

删除 continue; 后排 System.out.println("The integer you entered " + n + " is not a PRIME NUMBER!");

continue;做的是它跳过它之后的循环的所有部分并执行循环的下一次迭代。