本题的思路为将数组中所有数据标志量先初始化为0 ,再通过for循环遍历,将非素数的标志量置为1,最后再遍历输出标志量为0的数据。 import java.util.Scanner; public class P3912素数个数 { public static void main(String[] args) { int num=0; Scanner sc = new Scanner(System.in); int N = sc.nextInt(); int a[] =new int [N+1]; for(int i =0 ; i < a.length ; i++) { a[i] = 0; } for(int i = 2;i <= Math.sqrt(N);i++) { for(int j = i*2; j <= a.length-1;j+=i) { a[j]=1;//1说明已经删掉了 } } for(int j = 2; j< a.length;j++) { if(a[j]==0) { num++; } } System.out.println(num); } } 注意在最后一个for循环中,应当从int j = 2 开始循环。