java8--类的例子

1:有两个数组
int[] a1={123,38,103,89};
int[] b1={34,8,11,9};
求两个数组中所有的质数。
hello主函数的代码:

package my;

public class Hello {
    public static void main(String[] args) {


        PrimeFilter filter = new PrimeFilter();
        int[] a1 = {123, 38, 103, 89};
        int[] b1 = {34, 8, 11, 29};
        filter.put(a1);
        filter.put(b1);
        int[] numbers = filter.values();
        for (int i = 0; i < numbers.length; i++) {
            System.out.println("the result:" +numbers[i]);//数组在哪里输出就在哪里遍历
        }
    }
}
/*the result:103
the result:89
the result:11
the result:29
*/

PrimeFilter的代码:

package my;

public class PrimeFilter {
    public int[] result = new int[512];
    public int total = 0;

    //用户输入数组data;把data数组里面的所有质数存在result的数组里面
    public void put(int[] data) {
        for (int i = 0; i < data.length; i++) {
            if (this.isPrime(data[i])) {
                this.result[total] = data[i];
                this.total += 1;
            }
        }
    }

    //取出最终过滤得到所有的质数
    public int[] values() {
        int[] r = new int[total];
        for (int i = 0; i < this.total; i++) {
            r[i] = this.result[i];
        }
        return r;
    }

    //判断n是不是质数;true是质数,false不是质数
    public boolean isPrime(int n) {
        for (int i = 2; i < n; i++) {
            if (n % i == 0) {
                return false;
            }
        }
        return true;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值