0

so by the title, I am trying to flip characters from one value, to the opposite value. For example, - would become +, and + would become minus. These are the only 2 values right now, but I was wondering how I should go about this. So far I have this

public static String flip(String s, int index) {
    System.out.print("suuuh");
    String k = s;
    ArrayList<Character> array = new ArrayList<>();
    for (Character c : k.toCharArray()) {
        array.add(c);
        System.out.print(c);
    }
    for (int i = 0; i > index; i++) {
        if (array.get(i) == '-') {

            array.set(i, '+');
        } else {
            array.set(i, '+');
        }

    }
    StringBuilder builder = new StringBuilder();
    for (Character c : array) {
        builder.append(c.toString());
    }
    return builder.toString();
}

but it does not flip the + to a - or vice versa.

1 Answers1

1

Your basic approach is correct, although I would recommend a HashMap to store the opposites.

The reason your code does nothing is because

for (int i = 0; i > index; i++) {

should be something else, probably

for (int i = 0; i < array.size(); i++) {

At the moment, the loop is terminating immediately.

Also, the else should be

array.set(i, '-');

Another improvement is that there is no point using a List<Character> for this; you can use the char returned by toCharArray() directly.

Paul Boddington
  • 37,127
  • 10
  • 65
  • 116