【问题标题】:StringBuffer's replace method is not working as it's supposed to beStringBuffer 的替换方法无法正常工作
【发布时间】:2018-02-28 08:27:44
【问题描述】:

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

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

6 7  
.......

...O...

.......

.......

.......

.......

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

OOO.OOO

OO...OO

OOO.OOO

OOOOOOO

OOOOOOO

OOOOOOO

我得到的输出:

OO...OO

OO...OO

OO...OO

OO...OO

OO...OO

OO...OO

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.
    }
}

【问题讨论】:

  • 为什么不在该代码中简单地 char[][] ?我认为这里不需要StringBuffer。并使用fill 将实例放在每个单元格中,而不是副本中。所以你最终在newArr 的每个单元格中都有s,相同的引用。

标签: java arrays replace stringbuffer


【解决方案1】:

你用Arrays.fill(Object[], Object)填充newArr

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

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

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

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

【讨论】:

  • 或者你可以用更简单、更有效的方法来创建一个二维数组。用你当前的算法循环它,你不应该有任何问题。
  • @AlexanderHeim 我同意,我在评论中声明;)如果需要,使用char[][]String[]。不变性可以防止这个问题。
  • 谢谢你们!它有帮助! :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-24
  • 2012-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-02
  • 2021-12-29
相关资源
最近更新 更多