使用?:三目运算符
以计算完数为例子。其中遍历参考了 CenterCover 的回答:
import java.util.*;
class Main {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int n = sc.nextInt();
Vector<Integer> ans = new Vector<>();
for (int i = 1; i <= n; i++) {
if (judge(i)){
ans.add(i);
}
}
Iterator<Integer> it = ans.iterator();
while (it.hasNext()){
System.out.format("%d%s",it.next(),it.hasNext()?" ":"\n");//控制格式
}
}
static boolean judge(int x){
Vector<Integer> factors = new Vector<>();
for (int i = 1; i*2 <= x; i++) {
if(x%i==0){
factors.add(i);
}
}
int sum = 0;
for (Integer k:factors
) {
sum+=k;
}
return sum==x;
}
}