Question: This is a minesweeper Java problem. I am trying to eliminate whitespace at the end of my output. I'm not sure what to do. For

This is a minesweeper Java problem. I am trying to eliminate whitespace at the end of my output. I'm not sure what to do. For input:

2 2

2

0 0

1 1

I get an output of

* 2

2 *

this is correct, but there is a hidden space after each ending character of the output. Any help would be much appreciated. hers my code so far:

import java.util.Scanner;

public class Minesweeper {

static boolean isValid(int row, int col, int[][] grid) {

if (row >= 0 && row < grid.length && col >= 0 && col < grid[row].length) {

return true;

}

return false;

}

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

int m = scanner.nextInt();

int n = scanner.nextInt();

int grid[][] = new int[m][n];

for (int i = 0; i < m; i++) {

for (int j = 0; j < n; j++) {

grid[i][j] = 0;

}

}

int b = scanner.nextInt();

for (int i = 0; i < b; i++) {

int row = scanner.nextInt();

int col = scanner.nextInt();

grid[row][col] = -1;

if (isValid(row - 1, col - 1, grid)) {

if (grid[row - 1][col - 1] != -1) {

grid[row - 1][col - 1]++;

}

}

if (isValid(row - 1, col, grid)) {

if (grid[row - 1][col] != -1) {

grid[row - 1][col]++;

}

}

if (isValid(row - 1, col + 1, grid)) {

if (grid[row - 1][col + 1] != -1) {

grid[row - 1][col + 1]++;

}

}

if (isValid(row, col - 1, grid)) {

if (grid[row][col - 1] != -1) {

grid[row][col - 1]++;

}

}

if (isValid(row, col + 1, grid)) {

if (grid[row][col + 1] != -1) {

grid[row][col + 1]++;

}

}

if (isValid(row + 1, col - 1, grid)) {

if (grid[row + 1][col - 1] != -1) {

grid[row + 1][col - 1]++;

}

}

if (isValid(row + 1, col, grid)) {

if (grid[row + 1][col] != -1) {

grid[row + 1][col]++;

}

}

if (isValid(row + 1, col + 1, grid)) {

if (grid[row + 1][col + 1] != -1) {

grid[row + 1][col + 1]++;

}

}

}

System.out.println();

for (int i = 0; i < m; i++) {

for (int j = 0; j < n; j++) {

if (grid[i][j] == -1) {

System.out.print("* ");

} else {

System.out.print(grid [i][j] + " ");

}

}

System.out.println();

}

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!