Reputation: 147
What I need to do is make a number generator that stops when it generates 10 and shows how many attempts there was until 10 was reached. I also have to use only while loops for this. Here's my code now:
public static int RandomOccurrence()
{
int randNumber = (int)(Math.random()*20 + 1);
int count = 0;
while(randNumber != 11){
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
and here's the function call:
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
But when I run the code it prints "the number generated is 2" infinitely.
Upvotes: 3
Views: 1554
Reputation: 424953
Here's a 1-liner:
long count = IntStream.generate(() -> (int)(Math.random() * 20 + 1))
.takeWhile(i -> i != 11).count();
See live demo.
Upvotes: 0
Reputation: 8945
I really prefer to point the user towards the answers for homework problems instead of giving them code that works. Because we're trying to "teach a man to fish."
The problem with the original code is that it must generate another random number within the while
loop. The simplest way to do this is to copy-and-paste the same function-call that you used to generate the first one.
P.S.: You'll very quickly now see that "there's more than one way to do it!"
Upvotes: 3
Reputation: 25
you should update your random number every time the while loop gets executed: So randNumber = (int)(Math.random()*20 + 1); should be inside the loop
public static int RandomOccurrence(){
int count = 0;
int randNumber = 0;
while(randNumber != 11){
randNumber = (int)(Math.random()*20 + 1);
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
public static void main(String...args){
int number = RandomOccurrence();
System.out.println("It took " +number +" tries before 10 was generated");
System.out.println();
System.out.println();
}
I hope I could help
Upvotes: 1
Reputation: 23079
Here's a fixed version of your code, which mostly involves moving the line that gets a random number into the while
loop:
public static int RandomOccurrence()
{
int randNumber = 0;
int count = 0;
while(randNumber != 10){//I changed the 11 to 10 because you said you wanted to stop at 10
randNumber = (int)(Math.random()*20 + 1);//added
System.out.println("The number generated is " + randNumber);
count = count + 1;
}
return count;
}
System.out.println(RandomOccurrence());
Sample result:
The number generated is 1
The number generated is 4
The number generated is 20
The number generated is 19
The number generated is 10
5
Upvotes: 5