嵌套for循环以每行打印七个数组元素

时间:2011-03-30 00:13:00

标签: java

我正在研究一个程序,它将2的幂,一直到2 ^ 2000,插入一个数组,然后在一行上打印7个数字。我已经把所有的东西都搞定了所以它有效,但我觉得有一个更好更清洁的方法...特别是围绕嵌套的for循环区域。我使用y--来减少主循环,但我觉得这不是很合适。代码:

public class powers {

   public static void main(String[] args){
      long arr[] = new long[2000];

      for (int x=0; x<2000; x++){
         arr[x] = (long) Math.pow(2, x);
       }


      for (int y=0; y<14;y++) {
         for (int z=0; z<7; z++) {
            System.out.print(arr[y++] + " ");
         }
         y--; // Decrement y by 1 so that it doesn't get double incremented when top for loop interates
         System.out.println(); // Print a blank line after seven numbers have been on a line
      }

      }

}

2 个答案:

答案 0 :(得分:6)

for (int i = 0; i < 2000; i ++) {
  System.out.print(arr[i]); // note it's not println
  if (i % 7 == 6) { // this will be true after every 7th element
    System.out.println();
  }
}

答案 1 :(得分:0)

以下代码更有效,因为它会随着它打印出来。你通过这种方式减少了再次遍历它们的成本。另外,正如评论中提到的那样,长期不能将值存储在这些权力的上部区域中。

public class powers {

    public static void main(String[] args){
        long arr[] = new long[2000];

        for(int x=0; x<2000; x++){

            arr[x] = (long) Math.pow(2, x);

            System.out.print(arr[x] + " ");

            if(x%7==6)
                System.out.println();

        }

        //because your loop doesn't end on a 7th element, I add the following:
        System.out.println();

    }

}