• Post Reply Bookmark Topic Watch Topic
  • New Topic

How could I get my for loop to return a single random value?  RSS feed

 
David Vach
Ranch Hand
Posts: 105
3
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi all, so what I am trying to do is return a random feature inside of my impulseCustomer class. The customer is supposed to buy a random car ad a random feature. However the way the code is written requires me to use a for loop in order to go through all the available features. However, since it is a for loop, it will go through all the available values, and print them all out. I only want this customer to purchase one random feature. How would I be able to select one randomly out of the for loop? Here is my code:

 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't need a for-loop.  From what I can see, Car has a getFeatures() method that returns a List.  You want an integer from 0 to getFeatures().size() - 1.  Look into Random.ints(origin, bound).
 
David Vach
Ranch Hand
Posts: 105
3
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just tried that, and I can see the logic behind it, but when printing my results I am still getting all of the available features being printed. Not jsut a random one for that car.
 
Knute Snortum
Sheriff
Posts: 4274
127
Chrome Eclipse IDE Java Postgres Database VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please post all of your code.  Or create a short, complete program that illustrates the problem.
 
David Vach
Ranch Hand
Posts: 105
3
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here is the code I am working with. The inventory references a .txt file that I can post if necessary. Here is the code:

 
Carey Brown
Saloon Keeper
Posts: 3310
46
Eclipse IDE Firefox Browser Java MySQL Database VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

You have a basic problem with generating a random number using size()-1. If you have a list of length 10 you'd want an index in the range of 0-9 inclusive. Math.random()*size() will be in the range of 0.0 - 9.999999, and when truncated by the (int) cast you get 0-9. When you do size()-1 you get a range of 0-8.

A better approach entirely would be

In your upgrade() method you are setting a local variable "featureRandom" and then tossing it away when the method returns;
 
David Vach
Ranch Hand
Posts: 105
3
Chrome Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks that really helped!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!