如何在一个字符串中随机返回一个大写字母?

4

我有一个字符串作为输入,我想将整个字符串转换为小写字母,除了一个需要大写的随机字母。

我尝试过以下方法: splited是输入字符串数组


Translated:

我有一个字符串作为输入,我想将整个字符串转换为小写字母,除了一个需要大写的随机字母。

我尝试过以下方法:splited是输入字符串数组

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

当我尝试打印该字符串时,它总是返回第一个字母大写,其余部分为小写。为什么它不返回随机字母而是第一个字母呢?祝好!

显然,“first”始终为“0”。那么,“word1”是什么? - Matt Ball
“first”是使用“Math.random() * word1”随机生成的。其中,“word1”是字符串的长度。 - user3353723
是的,我能看到。word1 的值是多少? - Matt Ball
为什么第一个数字总是0?我以为应该是 Math.random() * range - user3353723
word1的值为6,因为字符串是“author”。 - user3353723
强制转换为int太早了,尝试使用(int)(Math.Random() * word1)。 - vakio
3个回答

4
理解你的问题的关键是,你将零乘以word1。
你的代码 int first = (int) Math.random() * word1; 每次返回同样的数字,因为(int) Math.random()每次都返回零。
这是Math.random()的javadoc:
返回一个带有正号的double值,大于或等于0.0且小于1.0。
任何小于1且大于0的数,一旦转换为整数,就是零。这是因为浮点数被截断。

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

1
由于。
Math.random()

返回一个介于0和1之间的值,因此:
(int) Math.random()

这个值始终为零,因为零乘以任何数都是零。

(int) Math.random() * word1;

也总是零。你需要括号。

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接