newJavauser
newJavauser

Reputation: 53

How to use a loop to print random integers to multiple lines?

I'm trying to create a program that outputs 3 random integers per iteration selected by the user. When I execute the below all my numbers are on the same line. How can I run the loop so that it outputs 3 integers per line?

if (yourNumber == 3){
    while (playTimes > print){
        for (int i = 0; i < 3; i++){
            int pick = randomLotto.nextInt(10);
            sum += pick;
            System.out.print(pick + " ");
        }
    print++;
    }
}
System.out.println();
System.out.println("Sum = " + sum);

Here's the output:

4 9 3 3 1 3   
Sum = 23

Upvotes: 1

Views: 95

Answers (4)

hugh
hugh

Reputation: 2280

Your while loop appears to be missing a closing brace too. This should do it:

public static void main(String[] args) {
    Random randomLotto = new Random();

    int yourNumber = 3;
    int print = 0;
    int playTimes = 3;
    int sum = 0;

    if (yourNumber == 3) {
        while (playTimes > print) {
            for (int i = 0; i < 3; i++) {
                int pick = randomLotto.nextInt(10);
                sum += pick;
                System.out.print(pick + " ");
            }
            System.out.println();
            print++;
        }
    }
    System.out.println();
    System.out.println("Sum = " + sum);
}

Upvotes: 1

WasiF
WasiF

Reputation: 28847

while (playTimes > print)
{
   for (int i = 0; i < 3; i++)
   {
      int pick = randomLotto.nextInt(10);
      sum += pick;
      System.out.print(pick + " ");
   }
   System.out.println(); //this is the point you are missing
   print++;
}

Upvotes: 1

ljleppan
ljleppan

Reputation: 366

EDIT: Misread the question. Original answer removed.

Your System.out.println() is on the wrong line. Move it so that it is directly after the for block ends.

Upvotes: 1

Stefan Freitag
Stefan Freitag

Reputation: 3608

Per iteration you could store each of the random numbers in a separate variable and use those ones in a println-statement. The below code is not tested, but should do for your requirement.

for (int i = 0; i < 3; i++){
  int pick_1 = randomLotto.nextInt(10);
  int pick_2 = randomLotto.nextInt(10);
  int pick_3 = randomLotto.nextInt(10);
  sum = sum + pick_1 + pick_2 + pick_3;
  System.out.println(pick_1 + " "+ pick_2 + " " + pick_3);
}

Upvotes: 0

Related Questions