2011-03-30 30 views
0

我正在研究一个程序,它将2的权力插入到数组中,然后将它们全部打印出7个数字在一条线上。我已经算出所有的东西,所以它的工作原理,但我觉得有一个更好,更干净的方式来做到这一点...特别是围绕嵌套的循环区域。我使用y--减少主循环,但我觉得这不太合适。代码:嵌套for循环打印一行数组中的七个元素

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 
     } 

     } 

} 
+1

2^2000是否适合长? – Reinderien 2011-03-30 00:18:00

+0

我查了一下 - 长只有64位,所以答案肯定不是。 – Reinderien 2011-03-30 00:18:47

+0

你需要java.math.BigInteger这个... – amit 2011-03-30 00:20:14

回答

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(); 
    } 
} 
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(); 

    } 

}
+0

您的输出将以空行开头,并且不会以\ r \ n结尾 – amit 2011-03-30 00:30:34

+0

您认为这是一件坏事。我会解决它,只是为了让你快乐。给我一点时间。 – 2011-03-30 00:32:27

+0

看来这不是他所要求的,所以这是一个糟糕的想法..我不知道'以\ r \ n结尾(如果需要或不需要),但肯定不应该有一个空白线。 – amit 2011-03-30 00:33:55