Java 打印 1-100 素数并抛出给定范围内合数异常的程序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20840396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
program to print 1-100 prime number and throw exception for composite number in given range
提问by Farhan ALi
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.
我制作了一个程序来打印 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);
}
}
}
采纳答案by Dmitry Bychenko
I'd rather implement isPrime
method and call it
我宁愿实现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");
}
}
}
回答by Ivaylo Strandjev
You should add an else
clause to if (ctr == 2) {
and throw an exception in it. Have a look at the documentationon how to throw an exception.
您应该向其中添加一个else
子句if (ctr == 2) {
并在其中抛出异常。查看有关如何引发异常的文档。
回答by Lingeshwaran
put one more condition like. else if(ctr!=2){ throw new CompositeException("composite exception occurs");}
再放一个条件就好了。else if(ctr!=2){ throw new CompositeException("复合异常发生");}
回答by Vilas Kolhe
public void primeNumber(int n1, int n2){
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);
System.out.print(primeNo);
}