Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
461 views
in Technique[技术] by (71.8m points)

java - Print an array elements with 10 elements on each line

I just created an array with 100 initialized values and I want to print out 10 elements on each line so it would be somthing like this

0 1 2 3 4 5 6 7 8 9
10 11 12 13 14 15 16
...26

this is the code I used and I managed to do it for the first 10 elements but I couldn't figure out how to do it for the rest

public static void main(String[] args) {

    int[] numbers = { 0,1,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17};  
    int i, count = 0;

    for (i = 0; i < numbers.length; i++) {

        System.out.print(numbers[i] + " ");
        count++;

        if (count == 9)
            for (i = 9; i < numbers.length; i++)
                System.out.println(numbers[i] + " ");
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
    int[] numbers = new int[100];
    for (int i = 0; i < numbers.length; i++) {
        if (i % 10 == 0 && i > 0) {
            System.out.println();
        }
        System.out.print(numbers[i] + " ");
    }

This prints a newline before printing numbers[i] where i % 10 == 0 and i > 0. % is the mod operator; it returns the remainder if i / 10. So i % 10 == 0 when i = 0, 10, 20, ....


As for your original code, you can make it work with a little modification as follows:

int count = 0;
for (int i = 0; i < numbers.length; i++) {
   System.out.print(numbers[i] + " ");
   count++;
   if (count == 10) {
     System.out.println();
     count = 0;
   }
}

Basically, count is how many numbers you've printed in this line. Once it reaches 10, you print the newline, and then reset it back to 0, because you're starting a new line, and for that line, you haven't printed any numbers (yet).


Note that in above two solutions, an extra space is printed at the end of each line. Here's a more flexible implementation that only uses separators (horizontal and vertical) when necessary. It's only slightly more complicated.

static void print(int[] arr, int W, String hSep, String vSep) {
    for (int i = 0; i < arr.length; i++) {
        String sep =
            (i % W != 0) ? hSep :
            (i > 0)      ? vSep :
            "";
        System.out.print(sep + arr[i]);
    }
    System.out.println(vSep);
}

If you call this say, as print(new int[25], 5, ",", ". ");, then it will print 25 zeroes, 5 on each line. There's a period (.) at the end of each line, and a comma (,) between zeroes on a line.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...