这是我的代码:
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();
}
我的问题是在每行的末尾都会有一个空格,因为+“”。
如何删除每行末尾的空白
P、 如果这个线程已经存在,请将我链接到它,因为大多数空格解决方案都是字符串,并且只是使用。修剪();