Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to randomly return an Uppercase letter in a String?

Tags:

java

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

like image 936
user3353723 Avatar asked Mar 21 '23 04:03

user3353723


1 Answers

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.

like image 150
Justice Fist Avatar answered Mar 22 '23 17:03

Justice Fist