【发布时间】: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