This question already has an answer here:
-
How do I generate random integers within a specific range in Java?
64 answers
I have to select and return 1 random character out of a string using this method (separate from main method):
public static char selectAChar(String s)
I'm not sure how to select the random variable, and not sure if i should use a for loop. everything I've tried I couldn't get it to return the right variable type.
EDIT: heres the coding i have so far
public static void main(String args[])
{
Scanner kbd = new Scanner (System.in);
System.out.println("Enter a string: ");
String s = kbd.next();
selectAChar(s);
}
public static char selectAChar(String s)
{
}
i tried something using this for loop
for(int i = 0; i < s.length(); i++)
but i can't figure out how to choose a random character and return it.
public static char selectAChar(String s){
Random random = new Random();
int index = random.nextInt(s.length());
return s.charAt(index);
}
There are at least two ways to generate a random number between 0 and a number (exclusive), one is using a call to Random.nextInt(int)
the Javadoc reads in part returns a pseudorandom, uniformly distributed int
value between 0 (inclusive) and the specified value (exclusive) and String.charAt(int)
the Javadoc says (in part) returns the char
value at the specified index.
static Random rand = new Random();
public static char selectAChar(String s) {
return s.charAt(rand.nextInt(s.length()));
}
For a second way you might use String.toCharArray()
and Math.random()
like
public static char selectAChar(String s) {
return s.toCharArray()[(int) (Math.random() * s.length())];
}
And of course, you could use (the somewhat warty) toCharArray()[int]
and charAt(int)
with either method.
Since you are returning a value, your caller should save it
char ch = selectAChar(s);
And then you might format the input String
and print the random char
like
System.out.printf("'%s' %c%n", s, ch);