用某种方法在java中选择字符串中的随机字符
我必须使用与主方法不同的方法从字符串中选择并返回1个随机字符: 公共静态字符选择器字符串s 我不确定如何选择随机变量,也不确定是否应该使用for循环。我尝试过的所有方法都无法让它返回正确的变量类型 编辑:这是我到目前为止的编码用某种方法在java中选择字符串中的随机字符,java,string,random,methods,char,Java,String,Random,Methods,Char,我必须使用与主方法不同的方法从字符串中选择并返回1个随机字符: 公共静态字符选择器字符串s 我不确定如何选择随机变量,也不确定是否应该使用for循环。我尝试过的所有方法都无法让它返回正确的变量类型 编辑:这是我到目前为止的编码 public static void main(String args[]) { Scanner kbd = new Scanner (System.in); System.out.println("Enter a string: "); Str
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)
{
}
我试着用这个做循环
forint i=0;ipublic static char selectAChar(String s){
Random random = new Random();
int index = random.nextInt(s.length());
return s.charAt(index);
}
第二种方式,你可能会使用和喜欢
当然,您可以将有点粗糙的toCharArray[int]和charAtint用于任何一种方法
因为您正在返回一个值,所以调用者应该保存它
char ch = selectAChar(s);
然后您可以格式化输入字符串并打印随机字符,如
请告诉我们您尝试了什么。您是否需要生成随机数并将其分配到int中,然后使用charAt并定位随机int?您将如何打印随机字符?对于我的单元测试,我做了。。。String=你好世界;System.out.printlnselectACharstring;这就是你的意思吗?举个例子,你可以调用System.out.printlnselectAChars;用你的主要方法。是的,对不起。我试着这么做,但我只是有一个打字错误。非常感谢你的帮助
public static char selectAChar(String s) {
return s.toCharArray()[(int) (Math.random() * s.length())];
}
char ch = selectAChar(s);
System.out.printf("'%s' %c%n", s, ch);