user6153390
user6153390

Reputation:

Print the value of the array in a new line every 20 times

I have to make a program in which 200 random numbers between 1 and 100 are generated.

    // Create an array to generate 200 numbers
    int Numbers [] = new int [200];

    // Create an array to split the numbers up into 5 categories
    int Count [] = new int [5];

    // Start a new loop
    for (int i = 0; i < Numbers.length; i++) {
        // Generate numbers between 1 and 100
        Numbers [i] = (int) (Math.random () * 100) + 1;
    }

    // Sort the array from least to greatest
    Arrays.sort(Numbers);

Here is where the problem I'm having starts (I believe).

Every 20 lines, the program should display a new line and then continue on with printing the rest of the numbers.

My issue is that is seems like not all of the numbers are printing... I'm only getting a total of 190 numbers printed out of the 200 that were generated.

    // Start a new loop
    for (int i = 0; i < Numbers.length; i++) { 
        if (i % 21 != 0) {
            System.out.print(Numbers [i] + " ");  
        }
        else {
            System.out.print(Numbers [i] + "\n");
        }
    }

I would really appreciate it if someone could please help me out with the code on this.

Upvotes: 2

Views: 1654

Answers (3)

Milind Gokhale
Milind Gokhale

Reputation: 585

    for (int i = 1; i <= Numbers.length; i++) {
        //
        if (i >= 19 && i % 20 == 0) {
            //
            System.out.print(Numbers[i - 1] + "\n");
        }

        //
        else {
            //
            System.out.print(Numbers[i - 1] + " ");

        }

    }

Upvotes: -1

Yassin Hajaj
Yassin Hajaj

Reputation: 22005

Here is what your condition should look like

if (i % 20 != 0 || i == 0)

You should put a new line if i % 20 == 0 but not in the first case (0 % 20 == 0)


Simplification

for (int i = 0; i < Numbers.length; i++) {
    System.out.print(Numbers[i] + (i%20 != 0 || i == 0 ? " " : "\n"));
}

Upvotes: 1

Elliott Frisch
Elliott Frisch

Reputation: 201527

First, please use println or System.lineSeparator() (because '\n' isn't the line separator on every platform). You also need to use % 20 == 0 for every 20th number. Something like,

for (int i = 0; i < Numbers.length; i++) {
    if (i % 20 == 0) {
        System.out.println();
    } else {
        System.out.print(" ");
    }
    System.out.print(Numbers[i]);
}

or using a ternary like

for (int i = 0; i < Numbers.length; i++) {
    System.out.print(i % 20 == 0 ? System.lineSeparator() : " ");
    System.out.print(Numbers[i]);
}

Finally, by convention, Java variables start with a lower case letter. So please rename Numbers to lower case like numbers.

Upvotes: 1

Related Questions