如何设计boolean prime(int n)方法,可用来判别n是否为质数,若为质数,则响应为true,若不是,则响应为false,若n小于0,则抛出ArgumentOutOfBoundException。啊 ???
我闹了半天没弄出来,请给个可以运行的代码看看吧
我闹了半天没弄出来,请给个可以运行的代码看看吧
解决方案 »
- 线程锁的问题 不太清楚线程执行过程
- http://localhost:8080/article/UserFiles/File/林三0(1).doc 不能打开?
- 如何将int数组中得值保存为一个文件,然后再一个一个从文件中读去出来保存到一个新数组中
- jbuilder怎么把要用到的数据库添加进去
- 我们的网站访问量很大,同时并发可能有100多人访问数据库,但如果这时候有1个人在往一张表里写数据,那么mysql就会把整张表锁定,这时其它99
- 怎样用java在xml中插入数据啊?
- 请教关于不可变类String的问题。
- 关于方法在内存中的位置请教
- 菜鸟提问
- 请问谁做过ftp协议?
- 如何用JAVA得到远程主机的操作系统类型?
- PL/SQL中的for循环问题,在线等!
学习知识和帮助他人的意义远远不在这分数上,况且我今天刚发了好几个帖,肯定没结啊,那结贴率肯定低了。
你来CSDN要的只是分数吗?要多少?我全给你!
import java.io.*;
public class TestNum {
public static boolean prime(int n) throws ArgumentOutOfBoundException{
if (n < 0)
throw new ArgumentOutOfBoundException();
if (n == 0){
return false;
}
int m =(int)Math.sqrt(n);
for(int i = 2;i <= m;i++){
if (n % i == 0){
return false;
}
}
return true;
}
public static void main(String[] args) {
try {
boolean flag = false;
flag = prime(0);
System.out.println(flag);
} catch (ArgumentOutOfBoundException e) {
System.out.println("参数不能小于零!");
}
}
}
class ArgumentOutOfBoundException extends Exception {
public ArgumentOutOfBoundException(){}
}
public boolean Prime(int n) throws Exception{
boolean result = false;
if(n<0){
throw new Exception("ArgumentOutOfBoundException");
}
int count = 0;
for(int i=2;i<n;i++){
if(n%i==0){
count++;
}
}
if(count==0){
result = true;
}
return result;
}
public boolean Prime(int n) throws Exception{
boolean result = false;
if(n<0){
throw new Exception("ArgumentOutOfBoundException");
}
int count = 0;
for(int i=2;i<n;i++){
if(n%i==0){
count++;
}
}
if(count==0){
result = true;
}
return result;
}
--------------------------------------------
我在机器上运行过了,发现传的参数为负数时候运行后就报错,而不是打印出来("参数不能小于零!");
shuaiAWP 你是是看看是不是
--------------------------------------------
我在机器上运行过了,发现传的参数为负数时候运行后就报错,而不是打印出来("参数不能小于零!");
shuaiAWP 你是是看看是不是
没有错误import java.io.*;
public class TestNum {
public static boolean prime(int n) throws ArgumentOutOfBoundException{
if (n < 0)
throw new ArgumentOutOfBoundException();//n小于0抛出异常
if (n == 0){
return false;
}
int m =(int)Math.sqrt(n);
for(int i = 2;i <= m;i++){
if (n % i == 0){
return false;
}
}
return true;
}
public static void main(String[] args) {
try {
boolean flag = false;
flag = prime(-4);
System.out.println(flag);
} catch (ArgumentOutOfBoundException e) {//抛出异常后捕获,然后打印"参数不能小于零"
System.out.println("参数不能小于零!");
}
}
}
class ArgumentOutOfBoundException extends Exception {//定义自己的异常类
public ArgumentOutOfBoundException(){}
}