Win a copy of Cloud Native PatternsE this week in the Cloud forum
or Natural Language Processing in the AI/ML forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
  • Bear Bibeault
Sheriffs:
  • Paul Clapham
  • Knute Snortum
  • Rob Spoor
Saloon Keepers:
  • Tim Moores
  • Ron McLeod
  • Piet Souris
  • Stephan van Hulst
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Frits Walraven
  • Ganesh Patekar

Printing random integers in an array in Java

 
Ranch Hand
Posts: 65
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, as written in the title I would like to print let's say 10 random integers in an array. I came up with this little code put it prints twice as many numbers (hope it's correct english!) as expected, i.e 20. Any idea why ? Thanks.


output for exemple : 43 4 44 32 14 26 41 49 22 29 43 4 44 32 14 26 41 49 22 29
 
Rancher
Posts: 4175
47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You are printing both in the loop generating the random numbers and in the loop for printing the array.
Remove the print calls in the generation loop.
 
Frank Poupard
Ranch Hand
Posts: 65
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oups yes exactly...Thanks
 
Dave Tolls
Rancher
Posts: 4175
47
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No problem.
It's called code blindness. You've stared at something so long you can't see the issue. Getting someone else to look at the code with fresh eyes often results in a quick solution as they come in with no preconceptions.
We all get bouts of it, no matter how long you've been at this game.
 
Marshal
Posts: 65025
246
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Create an IntStream (Java8 only). Don't use Math#random, but a Random object:Afraid I haven't the time to explain any more now.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!