Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Randomly display rows

 
Sanober Shaikh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi
i am trying to generate a random number say(10) using r1= (int)(Math.random()*10+1);

now depending on the value the random no has generated i need to display the equivalent row say if 3 is generated the 3rd should
be displayed.

No number is to be repeated
so I'll have a check condition

My code is generating the random no,displaying the rows
if the no generated are stored in the array [2,3]

now if the next no generated is 3 it will give me a new number and if the number is 2 it will display 2nd row again

please let me know where i am wrong


 
Jan Cumps
Bartender
Posts: 2588
11
C++ Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
(hope I understood your problem correctly)

Your code is always going into the while() loop. When your random number is not duplicate, but also when the random number is duplicate.

You did not put a condition around while loop to prevent that it is executed on duplicates.
And if you detect a duplicate, you search for a new random number, and add it without checking if it is a duplicate (after System.out.println(r1+" Already present"); ) This might be a duplicate again.

And your while loops keeps on going, even if you have found the matching record.

Regards, Jan
 
Jeanne Boyarsky
author & internet detective
Marshal
Posts: 34681
367
Eclipse IDE Java VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sanober,
Welcome to JavaRanch!

How about removing the row from the list each time you pick an item. Then generate a random number one smaller each time. This will ensure you don't have duplicates.
 
Sanober Shaikh
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hey i still havent got a resolution of the duplicate entries, when my condition goes inside the else loop it should check with the array, if if has the value present or not,but it is not checking the condition, any suggestions

Regards
Sanober
 
Jan Cumps
Bartender
Posts: 2588
11
C++ Linux Netbeans IDE
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
when my condition goes inside the else loop it should check with the array, if if has the value present or not,but it is not checking the condition
Your else loop does not do that. It adds something to the array. It does not check the array.

You might not find the solution by looking at the code (speaking from my own experience) .
Take a fresh start and a deep breath. Go back to the drawing board and re-invent the logic.
Keep it as simple as you can.
Then code it as simply as you can.

Good luck, Jan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic