Reputation: 29
Essentially, my code is set to throw a default amount of darts (10,000) at a dartboard, which will calculate Pi. If no arguments are entered, there will be a default 10,000 darts being thrown If the user enters an argument, that argument will be the number of darts being thrown.
Right now, the program will run the for loop forever, without stopping. I realize that since my porgram isn't stopping, the for loop is not ending. It's an error with how I write the second conditional in the for loop, and how I intialize the numberOfDarts variable above, but I'm not sure what to do.
public class PiEstimator {
public static void main(String[] args) {
int numberOfThrows = 0;
if (args.length == 0) {
numberOfThrows = 10000;
}
if (args.length > 0) {
numberOfThrows = Integer.parseInt(args[0]);
}
if (Integer.parseInt(args[0]) < 0) {
System.out.println("Cannot throw a negative amount of darts");
}
int numberOfHits = 0;
System.out.println("start");
And the for loop is written like this (The loop itself works fine, I believe the error is within the conditions.)
for (int i = 0; i < numberOfThrows; i++) {
double x = Math.random();
double y = Math.random();
numberOfThrows++;
if (x*x + y*y <= 1) {
numberOfHits++;
System.out.println(x + " " + y + " in");
}
if (x*x + y*y > 1) {
System.out.println(x + " " + y + " out");
}
}
System.out.println("end");
System.out.println("Darts : " + numberOfThrows + " " + "Hits : " + numberOfHits + " " + "Pi Estimation : " + (4*((double)numberOfHits/(double)numberOfThrows)));
}
}
Upvotes: 1
Views: 838
Reputation: 393841
Remove this
numberOfThrows++;
Otherwise the loop won't terminate, since the stopping condition is i < numberOfThrows
, so if numberOfThrows
keeps growing, i
will never pass it (at least until numberOfThrows
overflows and becomes negative).
In addition, change your conditions to :
int numberOfThrows = 0;
if (args.length == 0) {
numberOfThrows = 10000;
}
if (args.length > 0) {
numberOfThrows = Integer.parseInt(args[0]);
if (Integer.parseInt(args[0]) < 0) {
System.out.println("Cannot throw a negative amount of darts");
}
}
You only want to check for a negative input when you know there is an input.
Upvotes: 3
Reputation: 7919
The problem is that you are increasing numberOfThrows
on every iteration of loop which causes the loop to be infinite.So suppose if
numberOfThrows=1
for (int i = 0; i <numberOfThrows ; i++) {
numberOfThrows++
numberOfThrows++ // if the if condition is also true
//next iteration loop would be
for (int i = 0; i < 3; i++) { // and increases for other iteration causing it infinite
Upvotes: 2
Reputation: 7082
You are increasing the number of throws here:
numberOfThrows++;
The loop never ends because it goes from 0 to numberOfThrows
, which keeps increasing. Remove this line and it will work fine.
Upvotes: 1