我制作了一个打印1-100个素数的程序。 请帮我在1到100个数字的范围内抛出复合数的异常。 我是初学者,所以任何帮助将不胜感激。
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 <= 100; i++) {
int ctr = 0;
for (x = i; x >= 1; x--) {
if (i % x == 0) {
ctr = ctr + 1;
}
}
if (ctr == 2) {
System.out.println(i);
}
}
}
答案 0 :(得分:3)
我宁愿实现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");
}
}
}
答案 1 :(得分:0)
您应该向else
添加if (ctr == 2) {
子句并在其中引发异常。看看the documentation如何抛出异常。
答案 2 :(得分:0)
再加上一个条件。 否则if(ctr!= 2){ 抛出新的CompositeException(“发生复合异常”);}
答案 3 :(得分:0)
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);
}