public static String jumble(String s) {
int length = s.length() - 2;
Random r = new Random();
int n = r.nextInt(2)+1;
int a = r.nextInt(length)+1;
String s1 ="";
if (s.length() < 4) {
s1 = s1 + s;
} else if (s.length() == 4) {
s1 = s1 + s.charAt(0);
s1 = s1 + s.charAt(2);
s1 = s1 + s.charAt(1);
s1 = s1 + s.charAt(3);
}
while (n == a) {
a = r.nextInt(length)+1;
}
if (0 < n && n < a && a < s.length()) {
s1 = s1 + s.substring(0,n) + s.charAt(a) + s.substring(n + 1, a) + s.charAt(n) + s.substring(a+1,s.length());
}
System.out.println(s1);
return s1;
这是我的要求
Stringjumble(String(:接受一个字符串并返回原始的混乱版本:对于此方法,jumbled 意味着交换字符串的第一个和最后一个字符以外的两个随机选择的字符;此方法必须使用类 Random。该方法必须交换两个不同的字符:换句话说,字符串中的两个随机索引不能相等,不能为 0,也不能等于字符串的长度减去 1。因此,例如,一个四个字母的字符串必须导致返回的字符串具有相同的第一个和最后一个字符,并交换第二个和第三个字符。此方法可能执行的示例:"fist"返回"fsit","much"返回"mcuh",但对于较长的字符串,将有更多可能的返回值:"spill"可以返回"splil"或"sipll"。只应交换一对字母,并且短于四个字符的字符串将保持不变。当字符串长度大于 3 时,不得返回原始字符串。
我必须使用随机类,并且只能使用长度、charAt 和子字符串的字符串类方法。 这就是我到目前为止所拥有的,当最后一个字符串大于 4 时,我真的需要帮助创建它,我需要使用我制作的随机数。
编辑:感谢Ursa,我现在的代码工作得更好了。 我现在遇到的问题,或者至少我认为这是一个问题是,有时代码并不总是打印或返回任何内容。
方法 #1
- 用
StringBuilder builder = new StringBuilder(s);
包装输入字符串 - 获取带有
builder.charAt(int)
字符并进行比较 - 用
builder.setCharAt(int, char)
交换字符 - 用
builder.toString()
取结果
而且你不需要触摸其他角色。
方法#2
首先,我们应该选择要交换的字符索引:
// 0 < i1 < i2 < s.length - 1
int i1 = 1 + r.nextInt(s.length() - 3); // 1 <= i1 <= s.length - 3
int i2 = 1 + i1 + r.nextInt(s.length() - i1 - 2); // i1 < i2 <= s.length - 2
然后我们应该按间隔拆分字符串:
[0, i1) - substring before the first swap char
{i1} - the first swap char
[i1 + 1, i2) - substring between swap chars
{i2} - the second swap char
[i2 + 1, s.length) - substring after the second swap char
最后我们应该交换 {i1} 和 {i2} 字符:
return s.substring(0, i1) + s.charAt(i2) + s.substring(i1 + 1, i2) + s.charAt(i1) + s.substring(i2 + 1, s.length);
试试这个:
public static String jumble(String s) {
int length = s.length();
StringBuilder sb=new StringBuilder(s);
int pos1 = getRandom(length);
int pos2 = getRandom(length);
while(pos1==pos2)
pos1=getRandom(length);
sb.setCharAt(pos1, s.charAt(pos2));
sb.setCharAt(pos2, s.charAt(pos1));
return new String(sb);
}
private static int getRandom(int length) {
Random r = new Random();
int rand=r.nextInt(length);
if(rand==0||rand==length)
return getRandom(length);
else
return rand;
}