2016-04-30 10 views
1

現在問題の解決方法を把握しようとしています。私は1000の乱数を印刷したいが、行ごとに20の数字しか印刷しない。別名、1000行の1行の代わりに、各行に20個の番号しか印刷されていません。ArrayListの各行を1000個の数字で区切るには、20個の数字しか印刷されません。

import java.util.*; 

public class ArrayListDemo { 
    static int pick; 
    public static void main(String args[]) { 
    // create an array list 
    ArrayList<Integer> al = new ArrayList(); 
    Random rand = new Random(); 
    for (int j = 0; j<1000; j++){ 
     pick = rand.nextInt(100); 
     al.add(pick); 
     if (j == 20){ 
     System.out.println(" "); 

     } 
    } 

    System.out.println(al); 

} 
} 

答えて

0

System.out.println( ""); j == 20の条件付きを削除してください。 ループを繰り返し、20点ごとに次の行を挿入します。

for(int x =0; x< al.size();x++) 
{ 
    System.out.print(al.get(x)+" "); 
// prints on the new line until the conditonal below is true again 
    if(x%20==0) 
    { 
     System.out.println(""); // moves to next line 
    } 


} 
+0

これは数字の大半のために働くように見えたが、その後、1000のヘルプをより多くの数字を印刷しているように見えましたか? –

+0

それ以上1000? – DarkV1

+0

ループが正しいです。それは "1000以上見えるかもしれませんが、1000の数字でなければなりません" – DarkV1

0
import java.util.*; 

public class ArrayListDemo { 

    public static void main(String args[]) { 
     ArrayList<Integer> list = new ArrayList<Integer>(); 
     Random r = new Random(); 
     for (int i = 0; i < 1000; i++) { 
      list.add(r.nextInt(100)); 
     } 
     for (int i = 0; i < list.size(); i++) { 
      if (i % 20 == 0 && i != 0) { 
       System.out.println(list.get(i) + " "); 
      } else { 
       System.out.print(list.get(i) + " "); 
      } 
     } 
    } 
} 
関連する問題