我正在开发一个程序,它将 2 的幂(一直到 2^2000)插入到一个数组中,然后将它们全部打印在一行上的 7 个数字中。我已经弄清楚了一切,所以它有效,但我觉得有一种更好、更干净的方法来做到这一点......特别是在嵌套的 for 循环区域周围。我使用 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
}
}
}
最佳答案
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();
}
}
关于java - 嵌套 for 循环以每行打印数组的七个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5480472/