我有一个for循环,它将3和7乘以1到100之间的所有数字。它只显示乘法后的数字小于100。你会如何对它进行排序以使其按升序排列?
for(int i = 1; i<=100; i++){
int result1 = 3 * i;
int result2 = 7*i;
if (result1 <=100){
System.out.println(+result1);
}
if (result2 <= 100){
System.out.println(+result2);
}
}
会使用另一个if语句对其进行排序吗?
答案 0 :(得分:3)
怎么样:
for(int i = 1; i<=100; i++){
if(i % 3 == 0 || i % 7 == 0)
System.out.println(i);
}
答案 1 :(得分:1)
听起来它会做你需要的:
[mike@mike ~]$ cat temp/SO.java
package temp;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class SO {
private static final int MAX_VAL = 100;
public static void main(String[] args) {
List<Integer> results = new ArrayList<Integer>();
for (int i = 1; i <= MAX_VAL; i++) {
int result1 = 3 * i;
int result2 = 7 * i;
if (result1 <= MAX_VAL) {
results.add(result1);
}
if (result2 <= MAX_VAL) {
results.add(result2);
}
}
Collections.sort(results);
System.out.println(results);
}
}
[mike@mike ~]$ javac temp/SO.java
[mike@mike ~]$ java temp.SO
[3, 6, 7, 9, 12, 14, 15, 18, 21, 21, 24, 27, 28, 30, 33, 35, 36, 39, 42, 42, 45, 48, 49, 51, 54, 56, 57, 60, 63, 63, 66, 69, 70, 72, 75, 77, 78, 81, 84, 84, 87, 90, 91, 93, 96, 98, 99]