如何将更改返回给String

时间:2015-01-23 19:43:08

标签: java swap

如何在我的Changer类中调整我的更改方法,以便它将执行所有添加的更改并返回带有更改的字符串?我在尝试在for循环中实现它时遇到了麻烦。输出不应该在字母上有任何重音符号。

public class Change {
    private char fromCharacter;
    private char toCharacter;

    public Change(char fromCharacter, char toCharacter) {
        this.fromCharacter = fromCharacter;
        this.toCharacter = toCharacter;
    }

    public String change(String characterString) {
        String newWord = characterString.replace(fromCharacter, toCharacter);
        return newWord;
    }
}

import java.util.ArrayList;

public class Changer {
    private ArrayList<Change> changes;

    public Changer() {
        this.changes = new ArrayList<Change>();
    }

    public void addChange(Change change) {
        this.changes.add(change);
    }

    public String change(String characterString) {
        String word = "";

        for (Change change : changes) {
            word = change.change(characterString);
        }   

        return word;
    }
}

public class Main {
    public static void main(String[] args) {
        Changer scandiesAway = new Changer();
        scandiesAway.addChange(new Change('ä', 'a'));
        scandiesAway.addChange(new Change('ö', 'o'));
        System.out.println(scandiesAway.change("ääliö älä lyö, ööliä läikkyy"));

    }
}

1 个答案:

答案 0 :(得分:1)

按如下方式更改方法;

班级Change

public String change(String characterString)  {       
  return characterString.replace(fromCharacter, toCharacter);  
}

班级Changer

public String change(String characterString) {

    for (Change change : changes) {
        characterString = change.change(characterString);
    }

    return characterString;
}