如何设计boolean prime(int n)方法,可用来判别n是否为质数,若为质数,则响应为true,若不是,则响应为false,若n小于0,则抛出ArgumentOutOfBoundException。啊 ???
我闹了半天没弄出来,请给个可以运行的代码看看吧
我闹了半天没弄出来,请给个可以运行的代码看看吧
解决方案 »
- 求高人指教,关于Java静态类
- 配置jdk7环境时为什么总无法加载主类 com.sun.tools.javac.Main?大家帮忙看看
- JAVA WEB 项目上传图片问题,请问大家都是如何实现的
- 我按书上编了一个程序FlowLayout,编译能通过,运行却出一个这样的对话框"我按书上编了一个程序Flowlayout,编译难过,运行就出一个框“ 该
- Java数组取值 期待多种方法 效率要高 新手 高手一起来 并不简单
- 请问一个动态编译的问题
- 有点疑问....
- 新增行并返回主键值问题
- 2003月07月06日升星,散分500!--分五天结贴之第五帖(最后一贴)。(次日凌晨零点结分)
- 请大虾解疑!关于Tomcat与Resin的区别,谢谢!!
- 如何用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(){}
}