3 Replies - 564 Views - Last Post: 25 March 2010 - 07:54 PM Rate Topic: -----

#1 aletty  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • 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  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 485
  • View blog
  • Posts: 2,690
  • Joined: 18-December 08

Re: Find random char in a string

Posted 25 March 2010 - 06:40 PM

When in doubt, add parentheses!

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.

Try this instead:
randomInt = (int) (Math.random() * inputText.length());

Was This Post Helpful? 1
  • +
  • -

#3 aletty  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • 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
Was This Post Helpful? 1
  • +
  • -

#4 pbl  Icon User is offline

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

Reputation: 8316
  • View blog
  • Posts: 31,836
  • 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
Was This Post Helpful? 1
  • +
  • -

Page 1 of 1