Reputation: 671
I am trying to create a method to make some of the word's letters visible and other ones *. This is actually a simple word guessing game. I ask the user to choose whether they want to give an answer or request a letter. For example if the answer is "ball" and user decides to request a word, ball should turn into "*a**".
That is the method I have came up with:
public static void showALetter(String correctAnswer) {
int randomLetterIndex = (int) Math.random() % (correctAnswer.length());
for (int i = 0; i < correctAnswer.length(); i++) {
if (i == randomLetterIndex) {
System.out.print(correctAnswer.charAt(randomLetterIndex));
} else {
System.out.print("*");
}
}
}
It only shows the first letter of the correct answer at every single request. What should I do ?
Upvotes: 1
Views: 77
Reputation: 104
Math.random() returns a number from zero to one. So, your randomLetterIndex will always be zero. Use this instead.
(int) (Math.random() * correctAnswer.length())
This will give a random number between 0 and correctAnswer.length() - 1.
Upvotes: 3
Reputation: 591
Math.random()
returns a double higher or equal than 0 and less then 1, (int) Math.random()
will always return 0.
Use
(int)(Math.random() * correctAnswer.length())
The modulo is useless here, this way you always hit inside the given string as (int)
cast returns the floor value so the result will never be equal or higher than correctAnswer.length()
.
Upvotes: 0
Reputation: 13169
Math.random()
returns a double
with a value between zero and one (technically [0.0, 1.0)
written as a mathematical interval). This is not what you want, so you instead need to use the newer java.util.Random
class:
Random random = new Random();
int randomLetterIndex = random.nextInt(correctAnswer.length());
The random.nextInt(int limit)
method will return a value from zero (inclusive) to limit
(exclusive) which is what you need here for your puproses.
If you're going to use random numbers over and over again, then create your Random
instance as a static class member and have your methods refer to that, so that you only create the object once.
Upvotes: 3