如何设计boolean prime(int n)方法,可用来判别n是否为质数,若为质数,则响应为true,若不是,则响应为false,若n小于0,则抛出ArgumentOutOfBoundException。啊 ???
我闹了半天没弄出来,请给个可以运行的代码看看吧

解决方案 »

  1.   


    学习知识和帮助他人的意义远远不在这分数上,况且我今天刚发了好几个帖,肯定没结啊,那结贴率肯定低了。
    你来CSDN要的只是分数吗?要多少?我全给你!
      

  2.   


    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(){}

    }
      

  3.   


           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;
    }
      

  4.   


           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;
    }
      

  5.   


    --------------------------------------------
    我在机器上运行过了,发现传的参数为负数时候运行后就报错,而不是打印出来("参数不能小于零!");
    shuaiAWP 你是是看看是不是 
      

  6.   


    --------------------------------------------
    我在机器上运行过了,发现传的参数为负数时候运行后就报错,而不是打印出来("参数不能小于零!");
    shuaiAWP 你是是看看是不是 
      

  7.   

    自己测试了一下
    没有错误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(){}

    }