我应该写一种方法,乱码一个单词,在一个不是第一个或最后一个字符的单词中转换两个字母。
我将i和j初始化为位置1和str.length() -1之间的随机整数。为什么这个循环不打印一个单词的加扰版本?
char[] chararray = word.toCharArray();
int i = (int) (Math.random() * ((word.length()-2) - (1)) + 1);
int j = (int) (Math.random() * ((word.length()-2) - (1)) + 1);
for (int x = 0; x < word.length(); x++)
{
if (x == i)
{
chararray[x] = word.charAt(i);
}
else if (x == j)
{
chararray[x] = word.charAt(j);
}
}
word = new String (chararray);
System.out.println(word);当我输入tofu时,它会重印tofu。我想输入“豆腐”,然后输出“豆腐”。
发布于 2015-06-09 03:24:11
我想你是在寻找以下几个
for (int x = 0; x < word.length(); x++)
{
if (x == i)
{
chararray[x] = word.charAt(j);
}
else if (x == j)
{
chararray[x] = word.charAt(i);
}
}在if和else块中交换i和j值。
当x等于i时,您要在chararray中分配相同的值,因此您将得到相同的值。但是你的意图是交换I和j位置上的角色。
还有一件事,确保我永远不等于j
发布于 2015-06-09 03:28:38
从字符数组开始。
使用随机生成器获取字符数组长度(排他性)和0(包括在内)之间的2个整数。
如果i != j,交换它们。(没有必要用自己交换字符)
public class QuickTester {
public static void main(String[] args) {
Random rand = new Random();
char[] charArr = "elephant".toCharArray();
// Using charArr.length - 2 + 1 to exclude first and last
int i = rand.nextInt(charArr.length - 2) + 1;
int j = rand.nextInt(charArr.length - 2) + 1;
if (i != j) {
System.out.printf("Going to swap %c at position %d "
+ "with %c at position %d%n", charArr[i], i, charArr[j], j);
char temp = charArr[i];
charArr[i] = charArr[j];
charArr[j] = temp;
System.out.println("\nResult: " + new String(charArr));
}
}
}结果:
Going to swap t at position 7 with e at position 2
Result: eltphane更新:
从charArr.length更改为charArr.length - 2 + 1,以排除第一个和最后一个字符。
发布于 2015-06-09 03:28:39
你的逻辑似乎错了,
if (x == i)
{
chararray[x] = word.charAt(i);
}以上只是指向相同的索引,x和我都指向相同的索引,您需要交换索引。
下面的代码
public static void main(String args[]) {
String word = "ankur";
char[] chararray = word.toCharArray();
int i = (int) (Math.random() * ((word.length() - 2) - (1)) + 1);
int j = (int) (Math.random() * ((word.length() - 2) - (1)) + 1);
System.out.println(i + " and " + j);
for (int x = 0 ; x < word.length() ; x++) {
if (x == i) {
chararray[x] = word.charAt(j);
} else if (x == j) {
chararray[x] = word.charAt(i);
}
}
word = new String(chararray);
System.out.println(word);
}输出
2 and 1
aknurhttps://stackoverflow.com/questions/30722428
复制相似问题