2011-11-01 77 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] 
相關問題