我正在尝试创建一个方法,将位置为p的char更改为字符串“s”中的char“c”。它需要是递归的,除了charAt()和lenght()之外,我不允许使用String类中的任何其他方法。但是,现在,它只返回null。请帮忙。
import java.util.*;
public class Main {
public static void main(String[] args) {
//Test
String S = new String("augusto");
Word W = new Word(S);
System.out.println(W.changeChar(S, 'x', 3));
}
}
class Word {
public static String s;
static int counter, length;
static char [] arrayChar = new char[length];
Word(String x){
this.s = x;
this.length = x.length();
this.arrayChar = new char[length];
this.counter = 0;
}
//This Method changes to char "c" from a string "s", given the position "p"
public static String changeChar(String s, char c, int p){
if(counter == (s.length()-1)){
String r = new String(arrayChar);
return r;
} else if(counter == p){
arrayChar[counter] = c;
counter = counter + 1;
changeChar(s, c, p);
} else {
arrayChar[counter] = s.charAt(counter);
counter = counter + 1;
changeChar(s, c, p);
}
return null;
}
}
答案 0 :(得分:0)
试试这段代码:
public class Main {
public static void main(String[] args) {
//Test
System.out.println(new Word("augusto").changeChar('x', 0));
}
}
class Word {
private int mLength;
private char [] arrayChar;
Word(String x){
this.mLength = x.length();
this.arrayChar = x.toCharArray();
}
public String changeChar(char c, int position) {
return changeChar(c, position, 0);
}
//This Method changes to char "c" from a string "s", given the position "p"
private String changeChar(char c, int position, int currentIndex){
if (currentIndex == mLength - 1) {
return new String(arrayChar);
} else if (currentIndex == position){
arrayChar[currentIndex] = c;
return new String(arrayChar);
} else {
return changeChar(c, position, currentIndex + 1);
}
}
}