在同一行上打印不同大小的arraylists

时间:2014-10-22 13:28:35

标签: java arraylist

代码:

r = getDouble();
double temp = 0.0;
double userInput = r;
for (i=0; temp<max; i++) {
temp += r;
    if (temp<1000) {
        Doublecol1.add(temp);
    } else if (temp<2000) { 
        Doublecol2.add(temp);
    }else if (temp<3000) {  
        Doublecol3.add(temp);
    }else if (temp<4000) {  
        Doublecol4.add(temp);
    }else if (temp<5000) {      
        Doublecol5.add(temp);
    }else if (temp<6000) {      
        Doublecol6.add(temp);
    }else if (temp<7000) {      
        Doublecol7.add(temp);
    }else if (temp<8000) {
        Doublecol8.add(temp);
    }else if (temp<9000) {  
        Doublecol9.add(temp);
    }else if (temp<10000) {     
        Doublecol10.add(temp);
    }
}


for (i=0;i<=Doublecol10.size();i++) {

System.out.printf("%-10s %-10s %-10s %-10s %-10s %-10s %-10s %-10s %-10s %-10s\n", Doublecol1.get(i), Doublecol2.get(i), Doublecol3.get(i), Doublecol4.get(i), Doublecol5.get(i), Doublecol6.get(i), Doublecol7.get(i), Doublecol8.get(i), Doublecol9.get(i), Doublecol10.get(i));

arraylists的长度不同,我不知道如何容纳这个。目前它给出了indexoutofbounds异常并且所有列都是相同的长度而不是打印arraylist中的所有数字         }

1 个答案:

答案 0 :(得分:0)

我不确定,但这可能就是你要找的东西:

public static void main(String[] args) {
    final int colCount = 10;
    final int maxRows = 5;

    final Random rnd = new Random(System.currentTimeMillis());
    final List<Double>[] doubles = new LinkedList[colCount];

    // initialize indices
    for (int i = 0; i < doubles.length; i++) {
        doubles[i] = new LinkedList<>();

        // fill with random values
        for (int j = 0; j < rnd.nextInt(maxRows) + 1; j++) {
            // random value + number of column
            doubles[i].add(rnd.nextDouble() + (i + 1));
        }
    }

    // test output
    final StringBuilder result = new StringBuilder();
    final DecimalFormat df = new DecimalFormat("0.0000000#");

    for (int i = 0; i < maxRows; i++) {
        for (List<Double> col : doubles) {
            result.append(String.format("%10s ", (col.size() > i) ? df.format(col.get(i)) : "          "));
        }
        result.append('\n');
    }

    System.out.println(result);
}