2011-11-01 107 views
0

我有一个for循环,乘以1和100之间的所有数字乘以3和7.它只显示乘数之后的乘数减去100。你会如何对它进行排序,使其按升序排列?如何按照for循环的升序对数字进行排序?

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语句来排序吗?

回答

3

如何:

for(int i = 1; i<=100; i++){ 
    if(i % 3 == 0 || i % 7 == 0) 
     System.out.println(i); 
} 
+0

什么是 '%' 符号实际上呢? – admjwt

+0

它返回余数([modulo operation](http://en.wikipedia.org/wiki/Modulo_operation)) – MByD

+0

@ratchetfreak - 例如,这将错过6和9。 – MByD

1

这听起来像它会做你需要的东西:

[[email protected] ~]$ 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); 
    } 
} 

[[email protected] ~]$ javac temp/SO.java 
[[email protected] ~]$ 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] 
相关问题