这是我的代码:
import java.util.*;
public class Main {
public static void fill(char mat[][], int x, int y, char prevV, char currV) {
if (x < 0 || x >= mat.length || y < 0 || y >= mat.length)
return;
if (mat[x][y] != prevV)
return;
mat[x][y] = currV;
fill(mat, x + 1, y, prevV, currV);
fill(mat, x - 1, y, prevV, currV);
fill(mat, x, y + 1, prevV, currV);
fill(mat, x, y - 1, prevV, currV);
}
public static void replace(char mat[][]) {
for (int i = 0; i < mat.length; i++)
for (int j = 0; j < mat.length; j++)
if (mat[i][j] == 'O')
mat[i][j] = 'v';
for (int i = 0; i < mat.length; i++)
if (mat[i][0] == 'v')
fill(mat, i, 0, 'v', 'O');
for (int i = 0; i < mat.length; i++)
if (mat[i][mat.length - 1] == 'v')
fill(mat, i, mat.length - 1, 'v', 'O');
for (int i = 0; i < mat.length; i++)
if (mat[0][i] == 'v')
fill(mat, 0, i, 'v', 'O');
for (int i = 0; i <mat.length; i++)
if (mat[mat.length - 1][i] == 'v')
fill(mat, mat.length - 1, i, 'v', 'O');
for (int i = 0; i < mat.length; i++)
for (int j = 0; j < mat.length; j++)
if (mat[i][j] == 'v')
mat[i][j] = 'X';
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int m = sc.nextInt();
char[][] mat = new char[n][m];
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
mat[i][j] = sc.next().charAt(0);
}
}
replace(mat);
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
}
}
我遇到问题的部分是主要方法,特别是这部分:
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
System.out.print(mat[i][j] + " ");
}
System.out.println();
}
我的问题是在每一行的末尾会有一个空格,因为+&#34; &#34;
如何删除每行末尾的空格
P.S。如果这个线程已经存在,请链接我,因为大多数空白解决方案都是使用字符串并且只使用.trim();
答案 0 :(得分:1)
不要在行的末尾给出空格字符。
你可以这样写:
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (j < m - 1)
System.out.print(mat[i][j] + " ");
else
System.out.println(mat[i][j]);
}
}
答案 1 :(得分:1)
为输出空格添加条件:
for (int j = 0; j < m; j++) {
System.out.print(mat[i][j]);
if (j < m - 1) {
System.out.print(" ");
}
}
答案 2 :(得分:0)
除了给出的答案,你可以这样做
for(int i = 0; i < n; i++) {
int j =0; //we move j outside so that it can be accessed later
for( ; j < m -1; j++) { //notice we skip the last entry of the row
System.out.print(mat[i][j] + " ");
}
System.out.println(mat[i][j]); //we add the last entry of the row here.
}
优势在于,您不需要在每次迭代时进行检查,并且对当前代码进行最小的更改。