You almost had it already. I think your main issue was this part:
int l = ((int)Math.random()*s.length());
Your (int)
cast is misplaced. If you read the javadoc of Math.random()
you see that it returns a double value "greater than or equal to 0.0 and less than 1.0". Casting values of this range to int
(i.e. simply cutting off all decimal places) will always result in 0
, which only prints the first character of the string.
The solution is to first multiply it with the string's length and do the cast afterwards:
int l = (int)(Math.random()*s.length());
If you only want to print one random character, you don't need a loop of any sort, so you can delete that from your code.
See this fiddle for a working example. What you still need to do is think about how to get the input string (hint: maybe read it from System.in
).
public static void main (String[] args) throws java.lang.Exception
{
String s = "foobar42";
int l = (int)(Math.random()*s.length());
char ch = s.charAt(l);
System.out.println(ch);
}
And to finally show off in class, you could also have a look at the Random
class which could replace the above line with something like
int l = new Random().nextInt(s.length());
and see if you can grasp the difference between those two approaches. Although that is completely irrelevant to your assignment and way out of scope.