guitartsword
guitartsword

Reputation: 62

Java: replaceAll doesn't work as I think it should

public class NewClass {
    public static void main(String[] args) {
            String piece = "10*2";
            String ans = "20";
            String problm = "10*2*9";

            System.out.println(piece);
            System.out.println(ans);

            problm.replaceAll(piece, ans);

            System.out.println(problm);
    }
}

This is my code, and when I print problm it prints: 10*2*9 I want it to print 20*9, please tell me what I'm doing wrong

Upvotes: 0

Views: 123

Answers (3)

August
August

Reputation: 12558

First of all, use replace instead of replaceAll. replaceAll uses regular expressions, which you probably don't want.

Secondly, Strings in Java are immutable, meaning that their value can never be changed. You need to assign the value of problm.replaceAll(piece, ans); back to problm:

problm = problm.replace(piece, ans);

Upvotes: 5

There are two separate problems here:

  1. replaceAll works with regular expressions. If you don't understand regular expressions yet, you probably want replace instead.

  2. You're ignoring the result of replaceAll, and printing the original string. You should print the result instead:

    String solution = problm.replace(piece, ans);
    System.out.println(solution);
    

    (Of course, you don't have to use a temporary variable, and you don't have to call it solution if you do)

Upvotes: 2

jnd
jnd

Reputation: 754

You need to assign that to problm again. A String is immutable and can not be changed.

Upvotes: 1

Related Questions