简体   繁体   中英

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

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.

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());

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM