user3353723
user3353723

Reputation: 219

How to randomly return an Uppercase letter in a String?

I have a string as an input and I wanted to convert the whole string to lowercase except one random letter which needs to be in uppercase.

I have tried the following: splited is the input string array

word1 = splited[0].length();
word2 = splited[1].length();
word3 = splited[2].length();
int first = (int) Math.random() * word1;
String firstLetter = splited[0].substring((int) first, (int) first + 1);
String lowcase1 = splited[0].toLowerCase();

char[] c1 = lowcase1.toCharArray();
c1[first] = Character.toUpperCase(c1[first]);
String value = String.valueOf(c1);

System.out.println(value);

When I try and print the string, it ALWAYS returns the first letter as capital and the rest of the string is lowercase. Why is it not returning random letters but the first letter.

Cheers

Upvotes: 4

Views: 2271

Answers (3)

Jef
Jef

Reputation: 1148

Because

Math.random()

Returns a value between 0 and 1, so

(int) Math.random()

Is always zero, and since zero multiplied by anything is zero

(int) Math.random() * word1;

Is also always zero. You need parenthesis.

int first = (int) (Math.random() * word1);

Upvotes: 1

Brian
Brian

Reputation: 7326

String str = "my string";
Random rand = new Random(str.length());

int upperIndex = rand.nextInt();

StringBuffer strBuff = new StringBuffer(str.toLowerCase());
char upperChar = Character.toUpperCase(strBuff.charAt(upperIndex));
strBuff.replace(upperIndex, upperIndex, upperChar);

System.out.println(strBuff.toString());

Upvotes: 2

Justice Fist
Justice Fist

Reputation: 111

The key to understanding your problem is that you've multiplied zero times word1.

Your code int first = (int) Math.random() * word1; is returning the same number every time because (int) Math.random() returns zero every time.

Here's the javadoc for Math.random()

Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

Any number less than 1 and greater than 0, once casted to an integer, is zero. This is because floating point numbers are truncated.

Upvotes: 4

Related Questions