Question:
A little Java help please?
omegajb24
2009-07-21 11:31:37 UTC
I am writing a program in which I need a dartboard to display random spots in which darts hit and then wait for user input to either quit or throw the darts again. I have this in a while loop but haven't quite figured out how to get the program to randomize the dart locations again.

The main loop:

System.out.print("Would You Like To Throw Darts (Y or N)? ");

String x = in.next();
int counter = 1;

while (!x.equalsIgnoreCase("N"))
{
panel.changeArrows();
counter++;

System.out.printf("Score is %d.%n", panel.scoring());
System.out.print("Another Round (Y or N)? ");
x = in.next();
}
System.exit(0);

changeArrow method it calls:

public void changeArrows()
{
showArrows = true;
repaint();
scoring();
}

The program is set up so that the arrows aren't drawn until the user declares they want to play. The panel is then repainted with the arrows on it. Everything works fine except the arrow locations never change. The arrows are objects created out of a separate arrow class. The randomization takes place in that arrow class. What would be a good way to get the arrows to randomize and repaint on the panel each time the user wants to play?
Four answers:
Daniel
2009-07-21 11:42:06 UTC
Separate the simulation logic from the display. Create a simple program to loop through the rounds logging the x,y coordinates of each arrow and the resulting score. Use java.util.Random to ensure that results are random. Tie the UI into the model by firing custom events for each round passing the arrow collection in the event data. Register an event listener in the UI to redraw the board when it receives one of these events.
viewtyjoe
2009-07-21 11:36:11 UTC
If your arrows are a separate class, your best bet is to add a method in the arrow class to change its position or to reinitialize your arrows every time the changeArrows method is called.
Kimberly
2009-07-21 11:47:33 UTC
When you set the location where you want the darts to be located, use Math.random();



Math.random() will place the darts on the board in random spots each time they play. Check the java docs for addition help.



http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Math.html#random()
RachelM
2009-07-21 11:38:48 UTC
Don't you need some kind of random or rand function in there if you want the positions of the arrows to be random?



I know a little bit of Java but not enough to tell you what to do to make it random (but I would assume you need some type of rand function in there).



Maybe this will help:



http://www.glenmccl.com/tip_010.htm

http://www.java-tips.org/java-se-tips/java.util/how-to-generate-a-random-number-3.html

http://www.exampledepot.com/egs/java.util/GenRandom.html

http://www.pushlets.com/api/nl/justobjects/pushlet/util/Rand.html


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...