0

I have a code in which I am using replace method on Java String, but it is not working.. Please point out the mistake..

static String[] cavityMap(String[] grid) {
    String[] ans = grid;
    for(int i = 1; i<= grid.length-2; i++){
        for(int j = 1; j<= grid[i].length()-2; j++){
            int e = Integer.parseInt(grid[i].charAt(j) + "");
            int t = Integer.parseInt(grid[i - 1].charAt(j) + "");
            int b = Integer.parseInt(grid[i + 1].charAt(j) + "");
            int l = Integer.parseInt(grid[i].charAt(j - 1) + "");
            int r = Integer.parseInt(grid[i].charAt(j + 1) + "");
        if(e > t && e > b && e > l && e > r){
            ans[i] = ans[i].replace("X",(ans[i].charAt(j) + ""));
            System.out.println(ans[i].replace("X",(ans[i].charAt(j) + "")));
        }
        }    
   }    
   return ans;
}

The code execution is going in if conditional part.. But it is printing the same value as before.. Why is it not replacing the String with "X".. Thanks in advance

8
  • 2
    Hint: Probably naming your variables in a better way would help. Commented Feb 19, 2018 at 18:20
  • Debug and/or unit-test. Commented Feb 19, 2018 at 18:22
  • 1
    I can't see what you're trying to achieve. Maybe give a little more context? Commented Feb 19, 2018 at 18:22
  • what is the input that is used? Commented Feb 19, 2018 at 18:22
  • have you tried loggin the these two values ans[i].charAt(j) and ans[i] Commented Feb 19, 2018 at 18:24

1 Answer 1

2
ans[i].replace("X",(ans[i].charAt(j) + ""))

will replace all occurences of "X" with ans[i].charAt(j) + "".

If your intention is to replace ans[i].charAt(j) + "" with "X" you will need to swap your params:

ans[i].replace((ans[i].charAt(j) + ""), "X")

Also, using concatenation with empty string to cause conversion from char to String is discouraged. Consider explicitly invoking Character.toString or String.valueOf

ans[i].replace(String.valueOf(ans[i].charAt(j)), "X")

or better yet, since your replacement is a single char, just work in that type

ans[i].replace(ans[i].charAt(j), 'X')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.