# Find random char in a string

Page 1 of 1

## 3 Replies - 810 Views - Last Post: 25 March 2010 - 07:54 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=164309&amp;s=ce1c19e1c5a1b96936190667b05541b5&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 aletty

Reputation: 1
• Posts: 5
• Joined: 25-March 10

# Find random char in a string

Posted 25 March 2010 - 06:26 PM

I could use a little help to find a random char in a string. I think I'm on the right track but as of now it's just printing the first char in the sentence... help is much appreciated.

public static char randomChar (String inputText)
{
char randomChar;
int randomInt;

randomInt = (int) Math.random() * inputText.length();
randomChar = inputText.charAt(randomInt);
return randomChar;

}

This post has been edited by aletty: 25 March 2010 - 06:30 PM

Is This A Good Question/Topic? 0

## Replies To: Find random char in a string

### #2 erik.price

• D.I.C Lover

Reputation: 486
• Posts: 2,690
• Joined: 18-December 08

## Re: Find random char in a string

Posted 25 March 2010 - 06:40 PM

What you have currently casts the result of Math.random() to int. The problem is that this method returns a double >= 0 and < 1, so casting to an int will make it 0 every time. Multiplying by the String's length is irrelevant obviously, since 0 times anything is still 0.

```randomInt = (int) (Math.random() * inputText.length());
```

### #3 aletty

Reputation: 1
• Posts: 5
• Joined: 25-March 10

## Re: Find random char in a string

Posted 25 March 2010 - 06:51 PM

Thank you so much for your response. Can't believe it was that simple, heh

### #4 pbl

• There is nothing you can't do with a JTable

Reputation: 8369
• Posts: 31,956
• Joined: 06-March 08

## Re: Find random char in a string

Posted 25 March 2010 - 07:54 PM

When needing int random number better to create a Random object and call it's getNextInt() method

Random ran = new Random();
int number = ran.nextInt(100); // number will be >= 0 and < 100