0

I have an assignment due for my java course and I cant figure out how to print out a random character from a string the user has input, can anyone lend a hand?

Currently I have some code that looks like this

            Scanner keyboard = new Scanner(System.in);          

            String input = keyboard.next();

            Random random = new Random();
            char index = random.charAt(input.length());

            System.out.println("Here is a random Character ");
            System.out.println(index);

B25Dec
  • 2,301
  • 5
  • 31
  • 54
  • You can generate a random number `r` between `0` and `string.length()` , and then return `str.charAt(r)`. (see https://stackoverflow.com/questions/5887709/getting-random-numbers-in-java) – Daniele Feb 26 '20 at 20:08

3 Answers3

0

Try this:

    Scanner keyboard = new Scanner(System.in);          

    String input = keyboard.next();

    Random random = new Random();
    char index = input.charAt(random.nextInt(input.length()));

    System.out.println("Here is a random Character ");
    System.out.println(index);
Pedro Lima
  • 1,576
  • 12
  • 21
0

Modify this line:

char index = random.charAt(input.length());

to

char index = input.charAt(random.nextInt(input.length()));

Random does not have a charAt method, rather String does. So you need to use charAt of the String and pass it an integer.

This integer should be the random number generated based of the length of the String. This can be created using random.nextInt(input.length()) which creates a random number from 0 to the length - 1.

Nexevis
  • 4,647
  • 3
  • 13
  • 22
  • ohhhhhhhhhhh ok, thanks for explaining. I was able to get the program to print a random int but couldn't figure out why charAt wasn't working. Thanks a ton =D – Bronson3123 Feb 27 '20 at 06:00
  • @Bronson3123 No problem, please accept one of the answers given here that best answered your question using the checkmark so the question gets marked as answered. – Nexevis Feb 27 '20 at 13:06
0

You can get random character from string like below:

Scanner keyboard = new Scanner(System.in);          

String input = keyboard.next();

Random rand = new Random();
int randomIndex = rand.nextInt(input.length());

System.out.println("Here is a random Character ");
System.out.println(input.charAt(randomIndex));

I hope it helps!

harsh pamnani
  • 1,191
  • 1
  • 10
  • 14