【训练1】计算素数
使用lambda表达式创建SingleNumInterface接口对象。抽象方法可以输出方法参数值以内的所以素数。SingleNumInterface 接口定义如下:
interface SingleNumInterface{
int[] getSingleNumInterface(int max);
}
/*【训练1】计算素数
* 使用lambda表达式创建SingleNumInterface接口对象。
* 抽象方法可以输出方法参数值以内的所以素数。SingleNumInterface
* 接口定义如下:
*
* interface SingleNumInterface{
* int[] getSingleNumInterface(int max);
* }
*
* */
package lambdabdshlcl;
import java.util.ArrayList;
interface SingleNumInterface{
int[] getSingleNumInterface(int max)throws MyException;
}
class MyException extends Exception{
public MyException(String message) {
super(message);
}
}
public class Xl1 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
SingleNumInterface s = (a) -> {
ArrayList<Integer> list = new ArrayList<Integer>();
if(a == 1) {
return new int[] {1}; // 返回数组1
}
if(a < 1) {
throw new MyException("输入的数必须是大于等于1的正整数!"); // 抛出异常
}
for(int i = 1;i <= a;i++) {
boolean flag = true; // 默认是素数
for(int j = 2;j < Math.sqrt(i);j++) {
if(i % j == 0) {
flag = false; // 不是素数
}
}
if(flag) {
list.add(i);
}
}
int[] array = new int[list.size()]; // 将Integer型数组,转换为int型数组
for(int i = 0;i < list.size();i++) {
array[i] = list.get(i);
}
return array;
};
int num = 99;
System.out.println(num+"以内的所有素数:");
try {
int[] result = s.getSingleNumInterface(num);
for(int a : result) {
System.out.print(a + " ");
}
}catch(MyException e) {
System.err.println(e); // 控制台打印异常警告
}
}
}