Java 在ArrayList赋值中置乱某些字母
这项作业包括对由大写字母组成的字符串进行推理。您将实现几个出现在同一类中的静态方法(未显示)。详情如下。 1.第一个方法接受单个字符串参数并返回该字符串的加扰版本。置乱过程从单词的第一个字母开始,从左到右继续。如果两个连续的字母由一个“A”后跟一个非“A”的字母组成,则这两个字母在结果字符串中交换。两个相邻位置的字母交换后,这两个位置中的任何一个都不能参与未来的交换。 公共静态字符串加扰字(字符串字) 该方法接受给定的单词(空字符串或仅包含大写字母的字符串),并根据上面给出的规则返回包含单词加扰版本的字符串。下表显示了几个单词及其加扰版本的示例。 置乱后的原始单词 “TAN”“TNA” “ABRACADABRA”“BARCADABARA” “哇”“哇” 土豚 “蛋”“蛋” “A”“A” “” 我用过但不起作用的代码是Java 在ArrayList赋值中置乱某些字母,java,Java,这项作业包括对由大写字母组成的字符串进行推理。您将实现几个出现在同一类中的静态方法(未显示)。详情如下。 1.第一个方法接受单个字符串参数并返回该字符串的加扰版本。置乱过程从单词的第一个字母开始,从左到右继续。如果两个连续的字母由一个“A”后跟一个非“A”的字母组成,则这两个字母在结果字符串中交换。两个相邻位置的字母交换后,这两个位置中的任何一个都不能参与未来的交换。 公共静态字符串加扰字(字符串字) 该方法接受给定的单词(空字符串或仅包含大写字母的字符串),并根据上面给出的规则返回包含单词加扰
public class ScrambleWord {
public static void main(String[] args) {
List<String> strList = new ArrayList<String>();
strList.add("TAN");
strList.add("ABRACADABRA");
strList.add("WHOA");
strList.add("EGGS");
strList.add("A");
strList.add("");
System.out.prentln(MainMethod.scrambleWordMeth(strList));
}
class MainMethod {
public static void scrambleWordMeth(List<String> strList) {
int curr = 0;
String res = "";
while (curr < strList.size()) {
String currentString = strList.get(curr);
for(int i = 0; i < currentString.length(); i++){
if (currentString.charAt(i) == 'A' && !(currentString.charAt(i + 1) == 'A')) {
res = res + currentString.substring(curr + 1, curr + 2);
res = res + 'A';
curr = curr + 2;
}
else {
res = res + currentString.substring(curr, curr + 1);
curr++;
}
}
if (curr < strList.size()) {
res = res + currentString.charAt(curr);
//res=res + strList.substring(curr);
}
}
return res;
}
}
}
公共类加扰字{
公共静态void main(字符串[]args){
List strList=new ArrayList();
strList.添加(“TAN”);
strList.add(“ABRACADABRA”);
strList.add(“哇”);
添加(“鸡蛋”);
strList.添加(“A”);
strList.加上(“”);
System.out.prentln(MainMethod.scrambleWordMeth(strList));
}
类main方法{
公共静态无效置乱WordMeth(列表strList){
int curr=0;
字符串res=“”;
while(curr
以下是如何设置方法的模板,以便能够以更清晰、更独立的方式处理算法(请注意“多个方法”的任务状态)。这将防止发布的代码中出现一些问题,例如在内部循环中错误使用curr
(与字符完全无关)。字母数组的使用使任务本身更具逻辑性,无需执行切片和串联
static void scrambleAllWords(List<String> words) {
// Iterate through the list of word applying the scramble
// function and replacing the original item with the result.
for (int i = 0; i < words.size(); i++) {
String scrambled = scrambleWord(words.get(i));
words.set(i, scrambled);
}
}
static String scrambleWord(String word) {
// Get the letters that make up the word
char[] letters = word.toCharArray();
// Perform the algorithm on the letters
// for (int i = 0; i < ..
// Create a new string from the now-scrambled letters
return new String(letters);
}
请编辑你的帖子。它不可读(我同意上面的说法——正确的段落用法会产生巨大的差异。)我想要的是,如果一个以太后面没有跟a,或者后面没有最后一个a,就只加上字母aword@north.star我稍微更新了伪代码,使循环范围更清晰。循环应该超过
[0,letters.length-1)
。也就是说,如果单词中有8个字母,循环i超过[0,7)
(这样我将是0..6,包括在内)。这将意味着字母[i]
最多是字母[6]
(它甚至不会像最后一个字母那样寻找“A”)和字母[i+1]
(在检查第二个字母时)最多为字母[7]
,该字母始终保证为单词中的字母。