StringBuffer的替换方法不能正常工作

Sam*_*dal 2 java arrays replace stringbuffer

下面是一个代码,如果我遇到数组(arr)中的字母O,那么我必须用"."替换相同的数组索引(newArr).连同其相邻索引,即索引(i,j),(i + - 1,j)和(i,j + - 1)需要用"."替换.

考虑数组(arr)的这个输入:

6 7  
.......

...O...

.......

.......

.......

.......
Run Code Online (Sandbox Code Playgroud)

我应该使用数组(newArr)得到什么输出:

OOO.OOO

OO...OO

OOO.OOO

OOOOOOO

OOOOOOO

OOOOOOO
Run Code Online (Sandbox Code Playgroud)

我得到的输出:

OO...OO

OO...OO

OO...OO

OO...OO

OO...OO

OO...OO
Run Code Online (Sandbox Code Playgroud)

PS:我知道角落的情况,如果我们在索引中得到一个O,将导致ArrayIndexOutOfBound异常.请考虑上面的例子.

import java.util.*;

public class Pattern{

public static void main(String[] args){

    Scanner sc= new Scanner(System.in);

    int R= sc.nextInt(); // Takes input for Rows

    int C= sc.nextInt(); // Takes input for Coloumn

    StringBuffer[] arr= new StringBuffer[R]; // Array of type StringBuffer to which input is given.

    StringBuffer[] newArr= new StringBuffer[R]; // Array of type StringBuffer which shall be filled with alphabet "O".

    for(int i=0; i<R; i++)

        arr[i]= new StringBuffer(sc.next()); // Input given to array arr.

    StringBuffer s= new StringBuffer(); // A new stringBuffer 

    for(int i=0; i<C; i++)

        s.append("O"); // appends the required amount of alphabet O for newArr.

    Arrays.fill(newArr, s); // fills the array with s(which contains only alphabet O).

    for(int i=0; i<R; i++){
        for(int j=0; j<C; j++){
             if(arr[i].charAt(j) == 'O'){
                            newArr[i].replace(j, j+1, "."); // replaces "O" with "." in newArr.
                            newArr[i].replace(j+1, j+2, "."); // replaces "O" with "." in newArr.
                            newArr[i].replace(j-1, j, "."); // replaces "O" with "." in newArr.
                            newArr[i+1].replace(j, j+1, "."); // replaces "O" with "." in newArr.
                            newArr[i-1].replace(j, j+1, "."); // replaces "O" with "." in newArr.
            }
        }
    }
    for(int i=0; i<R; i++)
        System.out.println(newArr[i]); // printing the new replaced array.
    }
}
Run Code Online (Sandbox Code Playgroud)

Axe*_*elH 5

Sicne您填写的newArrArrays.fill(Object[], Object)

将指定的Object引用分配给指定的Objects数组的每个元素

您在每个单元格中放置相同的实例.所以你正在使用StringBuffer这里的1个实例.这意味着如果在一个单元格中进行更新,则每个单元格都将具有相同的更新(仅使用一个对象)

您需要为每个单元格创建一个副本(在数组上循环).

for(int i = 0; i < newArr.length; ++i){
    newArr[i] = new StringBuffer(s.toString());
}
Run Code Online (Sandbox Code Playgroud)