java 使用某种方法在java中的字符串中选择一个随机字符
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28512351/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
selecting a random char in a string in java with a certain method
提问by kiffffffkroker
I have to select and return 1 random character out of a string using this method (separate from main method):
我必须使用此方法(与 main 方法分开)从字符串中选择并返回 1 个随机字符:
public static char selectAChar(String s)
公共静态字符 selectAChar(String s)
I'm not sure how to select the random variable, and not sure if i should use a for loop. everything I've tried I couldn't get it to return the right variable type.
我不确定如何选择随机变量,也不确定是否应该使用 for 循环。我尝试过的一切都无法让它返回正确的变量类型。
EDIT: heres the coding i have so far
编辑:这是我到目前为止的编码
public static void main(String args[])
{
Scanner kbd = new Scanner (System.in);
System.out.println("Enter a string: ");
String s = kbd.next();
selectAChar(s);
}
public static char selectAChar(String s)
{
}
i tried something using this for loop for(int i = 0; i < s.length(); i++) but i can't figure out how to choose a random character and return it.
我尝试使用这个 for 循环 for(int i = 0; i < s.length(); i++) 但我不知道如何选择一个随机字符并返回它。
回答by shirrine
public static char selectAChar(String s){
Random random = new Random();
int index = random.nextInt(s.length());
return s.charAt(index);
}
回答by Elliott Frisch
There are at least two ways to generate a random number between 0 and a number (exclusive), one is using a call to Random.nextInt(int)
the Javadoc reads in part returns a pseudorandom, uniformly distributed int
value between 0 (inclusive) and the specified value (exclusive)and String.charAt(int)
the Javadoc says (in part) returns the char
value at the specified index.
至少有两种方法可以生成 0 到一个数字(不包括)之间的随机数,一种是使用调用Random.nextInt(int)
Javadoc 读取部分返回一个伪随机的、均匀分布int
在 0(包括)和指定值(不包括)之间的值并且String.charAt(int)
Javadoc 说(部分)返回char
指定 index 处的值。
static Random rand = new Random();
public static char selectAChar(String s) {
return s.charAt(rand.nextInt(s.length()));
}
For a second way you might use String.toCharArray()
and Math.random()
like
对于您可能使用String.toCharArray()
和Math.random()
喜欢的第二种方式
public static char selectAChar(String s) {
return s.toCharArray()[(int) (Math.random() * s.length())];
}
And of course, you could use (the somewhat warty) toCharArray()[int]
and charAt(int)
with either method.
当然,你可以使用(有点疣)toCharArray()[int]
和charAt(int)
任何一种方法。
Since you are returning a value, your caller should save it
由于您正在返回一个值,您的调用者应该保存它
char ch = selectAChar(s);
And then you might format the input String
and print the random char
like
然后你可以格式化输入String
并打印随机char
像
System.out.printf("'%s' %c%n", s, ch);