加入收藏 | 设为首页 | 会员中心 | 我要投稿 北几岛 (https://www.beijidao.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

设计一个MyInteger类判断为偶数/奇数/素数(练习构造方法)

发布时间:2021-07-06 05:38:12 所属栏目:大数据 来源: https://blog.csdn.net/summoxj
导读://设计一个MyInteger类,这个类包括:一个名为value的int类型字段,存储这个对象表示的整数值:如果当前value值分别是偶数/奇数/素数,那么isEven()/isOdd()/isPrime()方法返回true;如果指定值分别是偶数/奇数/素数,那么isEven(int)/isOdd(int)/isPrime(in

//设计一个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;
?? ?}
}

(编辑:北几岛)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读