How to randomly return a lowercase letter in a string?

I have a string as input, and I wanted to convert the entire string to lowercase, except for one random letter, which should be in uppercase.

I tried the following: splited is an array of input strings

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 to print a string, it ALWAYS returns the first letter as capital, and the rest of the string is lowercase. Why does this not return random letters other than the first letter.

Greetings

+4
source share
3 answers

The key to understanding your problem is that you multiplied the word zero by word1.

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

javadoc Math.random()

, 0,0 1,0.

1 0, , , . , .

+4
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());
+2

Insofar as

Math.random()

Returns a value from 0 to 1, so

(int) Math.random()

Always equal to zero, and since zero times anything, it is equal to zero

(int) Math.random() * word1;

Also always equal to zero. You need a bracket.

int first = (int) (Math.random() * word1);
+1
source

Source: https://habr.com/ru/post/1532588/


All Articles