日期:2014-05-20  浏览次数:20627 次

求助!!!为什么输出素数会有9,27这些,还少了2?
import java.util.Scanner;
public class Primes
{
  public void primes()
  {
  System.out.println("请输入一个整数:");
  Scanner sc = new Scanner(System.in);
  int a = sc.nextInt();
  for(int i=2;i<=a;i++)
  {  
  for(int j=2;j<i;j++)
  {
  if(i%j==0)
  {
  break;
  }
  else
  {
  System.out.print(i+"\t");
  break;
  }
  }
   
  }
  }
  public static void main(String args[])
  {
  Primes p = new Primes();
  p.primes();  
  }
}

------解决方案--------------------
Java code
package com.c813;

import java.util.Scanner;

public class Primes {
    public void primes() {
        System.out.println("请输入一个整数:");
        Scanner sc = new Scanner(System.in);
        int a = sc.nextInt();
        for (int i = 2; i <= a; i++) {
            boolean b = true;
            for (int j = 2; j < i; j++) {
                if (i == 2) {
                    break;
                }
                if (i % j == 0) {
                    b = false;
                }
            }
            if (b == true) {
                System.out.println(i + "  ");
            }
        }
    }

    public static void main(String args[]) {
        Primes p = new Primes();
        p.primes();
    }
}