【发布时间】:2017-03-21 21:30:06
【问题描述】:
我正在编写一个 java 代码,它将一个单词中的一个随机字母与该单词中的另一个随机字母交换。
我需要将此代码应用于整个字符串。我遇到的问题是我的代码无法识别空格,因此每个字符串运行一次该方法,而不是每个单词运行一次。如何拆分输入字符串并将该方法分别应用于每个单词。这是我目前所拥有的。
import java.util.Scanner;
import java.util.Random;
public class Main {
public static void main(String[] args {
Scanner in=new Scanner(System.in);
System.out.println("Please enter a sentance to scramble: ");
String word = in.nextLine();
System.out.print(scramble(word));
}
public static String scramble (String word) {
int wordlength = word.length();
Random r = new Random();
if (wordlength > 3) {
int x = (r.nextInt(word.length()-2) + 1);
int y;
do {
y = (r.nextInt(word.length()-2) + 1);
} while (x == y);
char [] arr = word.toCharArray();
arr[x] = arr[y];
arr[y] = word.charAt(x);
return word.valueOf(arr);
}
else {
return word;
}
}
}
【问题讨论】: