Home > Back-end >  How would you go about adding a space between every random number?
How would you go about adding a space between every random number?

Time:09-04

I'm trying to get the console to output 100 random numbers between 0 and 50, all on the same line with a space between each. I have everything but the formatting for the space. I know I need to use the printf function, but am completely lost on how to properly impliment it. This is what I have so far, but the output formatting is incorrect.

public static void main(String[] args) {
  Random rand = new Random();
  for (int count = 0; count <=100; count  )
  {
    int randomNum = rand.nextInt(51);
    System.out.printf(" ", randomNum, randomNum);
  }
}

CodePudding user response:

[1] Your code actually prints 101 numbers. Embrace the logic computers (and java) applies to loops and 'the fences' (the start and end): The first number is inclusive, the second is exclusive. By doing it that way, you just subtract the two to know how many items there are. so, for (int count = 0; count < 100; count ) - that loops 100 times. Using <= would loop 101 times.

[2] You're making this way too complicated by focusing on the notion of 'there must be a space in between 2', as if the 2 is important. What you really want is just 'after every random number, print a space'. The only downside is that this prints an extra space at the end, which probably doesn't matter:

for (int count = 0; i < 100; count  ) {
  System.out.print(randomNum   " ");
}

is all you actually needed. No need to involve printf:

I know I need to use the printf function

No, you don't. No idea why you concluded this. It's overkill here.

If you don't want the extra space.. simply don't print it for the last number:

for (int count = 0; i < 100; count  ) {
  System.out.print(randomNum);
  if (count < 99) System.out.print(" ");
}

[3] You mention that the code shuold print it all 'on one line', which perhaps suggests the line also needs to actually be a line. Add, at the very end, after the loop, System.out.println() to also go to a newline before you end.

CodePudding user response:

Here's a version neither using a condition or a separate first print but avoiding any leading or trailing space.

public static void main(String[] args) {
    Random rand = new Random();
    String delim="";
    for (int count = 0; count <100; count  )//fixed as per comments elsewhere.
    {
        int randomNum = rand.nextInt(51);
        System.out.printf("%s", delim,randomNum);
        delim=" ";// Change this to delim="," to see the action!
    }
}

It's a classic faff to print out n items with n-1 internal separators.

PS: printf feels like overkill on this. System.out.print(delim randomNum); works just fine.

  • Related