问题
i have made a program to print 1-100 prime numbers. please help me to throw exception for composite number in range of 1-100 numbers. i am a beginner so any help will be appreciated.
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);
}
}
}
回答1:
I'd rather implement isPrime
method and call it
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");
}
}
}
回答2:
You should add an else
clause to if (ctr == 2) {
and throw an exception in it. Have a look at the documentation on how to throw an exception.
回答3:
put one more condition like. else if(ctr!=2){ throw new CompositeException("composite exception occurs");}
回答4:
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);
}
来源:https://stackoverflow.com/questions/20840396/program-to-print-1-100-prime-number-and-throw-exception-for-composite-number-in