程序打印1-100素数并在给定范围内抛出复合数的exception

我制作了一个打印1-100个素数的程序。 请帮我在1到100个数字的范围内抛出复合数的exception。 我是初学者,所以任何帮助将不胜感激。

public static void main(String[] args) { System.out.println("Prime numbers from 1 - 100 are :"); int i = 0; int x = 0; for (i = 1; i = 1; x--) { if (i % x == 0) { ctr = ctr + 1; } } if (ctr == 2) { System.out.println(i); } } } 

我宁愿实现isPrime方法并调用它

 public static boolean isPrime(int value) { if (value <= 1) return false; // There's only one even prime: that is two if ((value % 2) == 0) return (value == 2); int from = (int) (Math.sqrt(value) + 1); // You have to check possible divisors from 3 to sqrt(value) for (int i = 3; i <= from; i += 2) if ((value % i) == 0) return false; return true; } public static void main(String[] args) { ... for (int i = 1; i <= 100; ++i) { if (isPrime(i)) System.out.println(i); else { // i is not prime. You can do nothing, throw an exception etc // throw new MyException("Not a prime"); } } } 

你应该为if (ctr == 2) {添加一个else子句,并在其中抛出exception。 看看有关如何抛出exception的文档 。

再加上一个条件。 else if(ctr!= 2){throw new CompositeException(“复合exception发生”);}

public void primeNumber(int n1,int n2){

  String primeNo= ""; System.out.print("Prime number between " + n1 +" and "+ n2 + "is/are - "); for(int i = n1;i <=n2; i++) { int count = 0; for(int j=1; j<=i; j++) { if(i%j==0) { count = count + 1; } } if(count == 2) { primeNo = primeNo + i + ", "; } } 

是System.out.print(primeNo);

 }