
//设计一个MyInteger类,这个类包括:一个名为value的int类型字段,存储这个对象表示的整数值:如果当前value值分别是偶数/奇数/素数,那么isEven()/isOdd()/isPrime()方法返回true;如果指定值分别是偶数/奇数/素数,那么isEven(int)/isOdd(int)/isPrime(int)方法返回true
代码如下:
import java.util.Scanner;
public class Demo {
?? ?public static void main(String[] args) { ?? ??? ?MyInteger integer1=new MyInteger(11); ?? ??? ?System.out.println(integer1.isOdd()); ?? ??? ? ?? ??? ?Scanner sc=new Scanner(System.in); ?? ??? ?int num=sc.nextInt(); ?? ??? ?MyInteger integer2=new MyInteger(); ?? ??? ?System.out.print(integer2.isEven(num)); ?? ?}
}
//MyInteger类
public class MyInteger { ?? ?int value; ?? ? ?? ?//构造方法 ?? ?public MyInteger(int value){ ?? ??? ?this.value=value; ?? ?} ?? ?public MyInteger(){ ?? ?} ?? ? ?? ?public boolean isEven(){ ?? ??? ?if(value%2==0) ?? ??? ??? ?return true; ?? ??? ?else ?? ??? ??? ?return false; ?? ?} ?? ? ?? ?public boolean isOdd(){ ?? ??? ?if(value%2==0) ?? ??? ??? ?return false; ?? ??? ?else ?? ??? ??? ?return true; ?? ?} ?? ? ?? ?public boolean isPrime(){ ?? ??? ?for(int x=2;x<value-1;x++){ ?? ??? ??? ?if(value%x==0) ?? ??? ??? ??? ?return false; ?? ??? ?} ?? ??? ?return true; ?? ?} ?? ? ?? ?public boolean isEven(int num){ ?? ??? ?if(num%2==0) ?? ??? ??? ?return true; ?? ??? ?else ?? ??? ??? ?return false; ?? ?} ?? ? ?? ?public boolean isOdd(int num){ ?? ??? ?if(num%2==0) ?? ??? ??? ?return false; ?? ??? ?else ?? ??? ??? ?return true; ?? ?} ?? ? ?? ?public boolean isPrime(int num){ ?? ??? ?for(int x=2;x<num-1;x++){ ?? ??? ??? ?if(num%x==0) ?? ??? ??? ??? ?return false; ?? ??? ?} ?? ??? ?return true; ?? ?} }
(编辑:北几岛)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|