Java 2D array grid - java

So basically I am trying to make a 9x9 grid for a minesweeper game. I need the grid to be filled with question marks to represent a minefield that has not been selected yet. Ex: [?][?][?][?][?] Basically my question is how would I get my program to output an array of question marks like that?
import java.util.Scanner;
import java.util.Arrays;
public class H4_Minesweeper {
public static void main(String[] args) {
//Game Description and rules
System.out.println("Minesweeper is a very straightforward game, the rules are simple.");
System.out.println("Uncover a mine (x), and the game ends. Uncover an empty square (o), and you keep playing.");
System.out.println("A question mark (?) will represent tiles you have not uncovered yet.");
System.out.println("Uncover a number, and it tells you how many mines lay hidden in the eight surrounding squares.");
System.out.println("Use this information to carefully choose which squares to click.");
System.out.println("\n\n\n");
Scanner userin;
String[][] board = new String [9][9];
for (int r = 0; r<board.length;r++){
for (int c = 0; c <board.length;c++){
}
}
}
}

First, you must initialize the array by setting all its elements to "?":
String[][] board = new String [9][9];
for (int r = 0; r<board.length;r++){
for (int c = 0; c <board.length;c++){
board[r][c] = "?";
}
}
Then you can print it:
for (int r = 0; r<board.length;r++){
for (int c = 0; c <board.length;c++){
System.out.print (board[r][c] + " ");
}
System.out.println();
}

This should do it.
for (int r = 0; r<board.length;r++){
for (int c = 0; c <board.length;c++){
board[r][c] = "?"; // Initialize the cell
System.out.print("[" +board[r][c] + "]"); // Display the content of cell board
}
System.out.println(); // go to next line
}

Fill your 2d array with the String "?" for each of the grid spaces, and then, go row by row printing out the values of each array index
Filling array:
String[][] board = new String[9][9];
for(int y=0;y<9;y++){
for(int x=0;x<9;x++){
board[x][y] = "?";
}
}
Displaying the rows:
for (int r = 0; r<9;r++){
String line = "";
for (int c = 0; c <9;c++){
line+="["+board[c][r]+"]";
}
System.out.println(line);
}

Related

closed and open elements in an array

I am writing a code to indicate open and closed elements in a 2d array. An open element is represented with . and a closed element is represented with *. The first column in the array must be completely open whereas all the other columns must be closed. The output should be:
.**
.**
.**
The array is also going to vary in size as the user will determine how big the array is. I have managed to code a 2D array grid as this is not hard, however, I am trying to now use an if-statement to make the first column all open. I placed the if-statement within the nested loop:
import java.util.Arrays;
import java.util.Scanner;
public class trial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
int i;
int j;
for(i=0; i<grid.length; i++) {
for(j=0; j<grid[i].length; j++) {
grid[i][j] ='.';
if(grid[j].length > grid[0].length) {
System.out.println("");
}else {
System.out.print('*');
}
StdOut.print(grid[i][j]);
}
StdOut.println();
}
}
}
This, however, is giving me an output that looks like this:
*.*.*.
*.*.*.
*.*.*.
*.*.*.
I have tried placing the if-statement outside of this nested for-loop but I then get an error with my variables as they have not been defined. Any assistance as to how to fix this or make it that I can get values for my i and j variables outside of the for-loop would be greatly appreciated.
I slightly modify your code to make it fit the description.
i and j will vary when the loop proceeds, and should be accessed inside the loop only.
It seems that you want to change the content inside grid, which can be accessed outside the loop after processing.
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
int i;
int j;
for (i = 0; i < grid.length; i++) {
for (j = 0; j < grid[i].length; j++) {
grid[i][j] = '.';
if(j > 0) {
grid[i][j] = '*';
}
System.out.print(grid[i][j]);
}
System.out.println();
}
// you cannot access i/j outside the loop scope. instead, you can access the grid
System.out.println("Loaded array:");
Arrays.stream(grid).forEach(System.out::println);
}
Just check if the current column is 0 or not
Just a minor change will work here
I am writing only the main loop below
for(i=0; i<grid.length; i++) {
for(j=0; j<grid[i].length; j++) {
if(j == 0){ //0th column make it dot(.)
grid[i][j] ='.';
}
else { //For other columns put asterisk(*)
grid[i][j] = '*';
}
}
}
Here's a different way to think about 2D arrays. They are simply a 1D array where each element is itself another 1D array (a complete "row").
With that in mind, here's a different way to initialize and print the contents of the 2D array using a mixture of enhanced and indexed for loops:
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("What size square grid do you want? ");
int m = sc.nextInt();
char[][] grid = new char[m][m];
for(char[] row : grid) {
for(int col=0; col<row.length; col++) {
row[col] = (col == 0) ? '.' : '*';
}
}
for(char[] row : grid) {
for(char c : row) {
System.out.print(c);
}
System.out.println();
}
}
Output:
What size square grid do you want?
5
.****
.****
.****
.****
.****

Get matrix from a file Java

I currently have a text file in the format
matrix
row
a
b
c
row
d
e
f
row
g
h
i
row
j
k
l
matrix
row
m
n
o
p
q
row
r
s
t
u
v
I would like to convert this into two integer matrices (stored as 2 2D arrays), in the format
a b c
d e f
g h i
j k l
and
m n o p q
r s t u v
So far, I have created a Scanner object of the file and put each line in a text array:
Scanner sf = new Scanner(new File("C:\\textfiles\\matrices.txt"));
int maxIndex = -1;
String text[] = new String[10000]; // I added more than necessary for safety
while (sf.hasNext()){
maxIndex++;
text[maxIndex] = sf.nextLine();
}
sf.close();
This way, the text file is now contained in a string array, where each line is a new element of the array. Right now, I would like to partition the array into two arrays with each array being the matrices. How should I continue? (note: I am a total beginner and desire answers that are simple (no arraylist, hashmap, etc., and that's why this question is not a duplicate of How to read two matrices from a txt file in java because it uses BufferedReader, and there are other potential duplicate questions, so I would like to clear this up)
What I currently have after the top:
int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
while (counter < maxIndex){
if (counter = 0)
{
\\not yet written...
}
\\not yet written...
}
As #Rob said, it's really cumbersome to do this without dynamic data structures such as ArrayList's. But nevertheless, here's a code that does your job (considering you have only two matrices), without using any List's:
int counter = 0;
int iCounter = 0; // row
int jCounter = 0; // column
int matrix1[][];
int matrix2[][];
int rowSize = 0, numberOfRows = 0;
counter = 2;
while (!text[counter].equals("row") && !text[counter].equals("matrix")) {
counter++;
rowSize++;
}
//now we have the row size
numberOfRows = 1;
while (!text[counter].equals("matrix")) {
if (text[counter].equals("row"))
numberOfRows++;
counter++;
}
//now we have the total number of rows
matrix1 = new int[numberOfRows][rowSize];
counter = 2; //to start from the first matrix
//now counter should point to the first row of the first matrix
while (!text[counter].equals("matrix")) {
jCounter = 0;
while (!text[counter].equals("row")
&& !text[counter].equals("matrix")) {
matrix1[iCounter][jCounter++] = Integer.parseInt(text[counter]);
//supposing your input is Integers, otherwise, you can change
//it to the corresponding type (i.e. Long, Double, etc)
counter++;
}
iCounter++;
if (!text[counter].equals("matrix"))
counter++;
}
//now we finished with the first matrix, and the counter points to
//the first "row" of the second matrix, so we do the same thing again
rowSize = 0;
numberOfRows = 0;
int startOfSecondMatrix = counter + 2; //save this for later
counter += 2; // so that counter points to the first number
while (counter < text.length && !text[counter].equals("row")) {
counter++;
rowSize++;
}
numberOfRows = 1;
while (counter < text.length) {
if (text[counter].equals("row"))
numberOfRows++;
counter++;
}
matrix2 = new int[numberOfRows][rowSize];
counter = startOfSecondMatrix;
iCounter = 0;
while (counter < text.length) {
jCounter = 0;
while (counter < text.length && !text[counter].equals("row")) {
matrix2[iCounter][jCounter++] = Integer.parseInt(text[counter]);
counter++;
}
iCounter++;
counter++;
}
For each matrix we perform the same operations:
-We first go through the matrix to count its size to be able to initialize it, after that, we go row by row, and parse each number.
You might as well put all the work for one matrix into a function (and take care of the bounds) and call it as long you still have more matrices.
This does what you want. Unfortunately doing this with 2D arrays is considerably harder since once you set the size of an array its difficult to manage changing it. Therefore using ArrayList is much easier.
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class Main {
public static final String MATRIX = "matrix";
public static final String ROW = "row";
public static void main(String[] args) throws FileNotFoundException {
// Use correct file name here
Scanner sf = new Scanner(new File("matrices.txt"));
// This is a List of 2D Lists
List<List<List<String>>> matrices = new ArrayList<>();
// easier to process lines as we're reading them in so we
// only iterate over the file once
while (sf.hasNext()) {
boolean hasBeenProcessed = false;
String inputValue = sf.nextLine();
switch (inputValue) {
case MATRIX:
ArrayList<List<String>> matrix = new ArrayList<>();
matrices.add(matrix);
hasBeenProcessed = true;
break;
case ROW:
List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
currentMatrix.add(new ArrayList<String>());
hasBeenProcessed = true;
break;
}
if (!hasBeenProcessed) {
List<List<String>> currentMatrix = getMatrixBeingProcessed(matrices);
List<String> currentRow = getCurrentRow(currentMatrix);
currentRow.add(inputValue);
}
}
// Print out the results:
int i = 1;
for (List<List<String>> matrix : matrices) {
System.out.println("Matrix " + i);
for (List<String> row : matrix) {
for (String element : row) {
System.out.print(element + " "); // no newline until end of the row
}
System.out.println(); // new line
}
i++;
System.out.println(); // new line
}
}
private static List<String> getCurrentRow(List<List<String>> currentMatrix) {
int lastRow = currentMatrix.size() - 1;
return currentMatrix.get(lastRow);
}
private static List<List<String>> getMatrixBeingProcessed(List<List<List<String>>> matrices) {
int lastMatrix = matrices.size() - 1;
List<List<String>> currentMatrix = matrices.get(lastMatrix);
return currentMatrix;
}
}
Output:
Matrix 1
a b c
d e f
g h i
j k l
Matrix 2
m n o p q
r s t u v
Process finished with exit code 0
Since you don't want to use List and arrays can't be resized once initialized, this is not easy.
There are two ways: Read the file and initialize arrays knowing the size (as #Maaddy posted) or 'resizing' arrays. That's not possible but it is if you use Arrays.copyOf() so you can create a new array.
The idea is create a 'tridimensional' array where you can store: matrix, row and column; and then start to read the file.
Every time you find a word the entire array will be updated creating a new array with one length more.
If the word is 'matrix' the extra length will be added to the first position (the position who 'store' the matrix)
If the word is 'row' then the space will be added for the current matrix. So in this way, the current matrix will have one more array where store the column values.
If the word is other then is a value for the column. The column is resized and added to the correct position.
Note that if a word 'matrix' or 'row' is found, the new array is initialized with no length. This is because will be resized later, when is necessary.
The code is as follows:
//Initialize array with no positions
String[][][] arrays = new String[0][0][0];
Scanner sf = new Scanner(new File("path/matrices.txt"));
int matrix = -1;
int row = -1;
int column = -1;
while (sf.hasNext()){
String line = sf.nextLine();
if(line.equals("matrix")) {
//'Resize' array: Create new array with 1 more length and old data
arrays = Arrays.copyOf(arrays, arrays.length + 1);
//Start new matrix
arrays[++matrix] = new String[0][0];
row = -1;
column = -1;
}else if(line.equals("row")) {
//'Resize' matrix: Create a new array with 1 more length and old data
arrays[matrix] = Arrays.copyOf(arrays[matrix], arrays[matrix].length+1);
row++;
arrays[matrix][row] = new String[0];
column = -1;
}else{
//'Resize' matrix
column++;
arrays[matrix][row] = Arrays.copyOf(arrays[matrix][row], arrays[matrix][row].length+1);
arrays[matrix][row][column] = line;
}
}
sf.close();
//Print result
for(int i = 0 ; i < arrays.length; i++) {
System.out.println("Matrix "+i);
for(int j = 0; j < arrays[i].length; j++ ) {
for(int k = 0; k < arrays[i][j].length; k++) {
System.out.print(arrays[i][j][k]+ " ");
}
System.out.println();
}
System.out.println();
}
And the result is:
Matrix 0
a b c
d e f
g h i
j k l
Matrix 1
m n o p q
r s t u v

How to print parts of an 2d array

Im not asking for the answer per say im asking necessarily what would i need to change in order to print out sections of a 2d array for example if the array has 5 rows and 5 columns how would i print out the last 3 rows and last three columns.
import java.util.Scanner;
public class multiplication {
static int a,b;
public static void main(String[] args){
Scanner input = new Scanner(System.in);
a =input.nextInt();
b = input.nextInt();
int[][] matrix = new int[a][b];
matrix = timesTable(a,b);
for (int row = 0; row < matrix.length; row++) {
for (int column = 0; column < matrix[row].length; column++) {
System.out.print(" "+matrix[row][column] + "\t|");
}
System.out.println();
}
}
public static int[][] timesTable(int r, int c)
{
int [][] yes = new int[c][c];
for ( r = 0; r < yes.length ; r++)
{
for (c = 0; c < yes[r].length; c++)
{
yes[r][c] = (r+1)*(c+1);
}
}
return yes;
}
}
if((row = 0 && col > 1) ||( row > 1 && col != 1)) {
//print
}
This logic should work for your example. But I don't understand what you're trying to do.
Can you try explain a bit more what you want to do ?
Edit: you might wanna check this. Oracle documentation bottom of the page with arraycopy and arraymanipulation
Is the goal of this exercise to build the matrix and then print the matrix -or- do you simply need to display the desired output? I assume this is a class assignment.
Hint: Think about this .. if you enter 2 & 5, do you want a 2x5 matrix or a 4x4 matrix? It's important when you alloc your matrix size.

Input of a 2D array via button and .txt file Processing Java

After a thorough survey of this and many other Internet communities I failed to solve my problem. It is about ControlP5 button and my aim of importing 2D array from previously formated text file with two columns and 19 rows and space separated values. Now my code works but the 2D arrray I designated to hold the values from the txt does not get all of the values but just the last pair in its first row. I know that for loops over all values but stores them only in the first row. I dont know how to push it in another row for reading. This is my code:
if(theEvent.isController())
{
if(theEvent.controller().name() == "mean shape males")
{
String loadPath1 = selectInput();
reader = createReader(loadPath1); //new BufferedReader
int x=0; //rows
int y=0; //columns
String smaLine;
try
{
while ((smaLine = reader.readLine()) != null)
{
String[] values = smaLine.split(", ");
for(int i = 0; i < values.length; i++)
{
float[] testC = float(split(values[i], " "));
for (int j = 0; j < testC.length; j++)
{
mat1[j][i] = testC[j]; //THIS IS THE PROBLEMATIC MATRIX
}
}
x = x+1;
}
}
catch (IOException e)
{
e.printStackTrace();
}
mat1max = maxRet(mat1);
mat1min = minRet(mat1);
inputMat = new Grid(2,19,10,130,22,mat1,mat1min,mat1max);
}
}
I used all the advice I could find on Stack Overflow mainly from this post How to print 2D Array from .txt file in Java but I just can`t seem to move the reader onto rows other then the first.
I'm guessing that instead of resetting the elements in mat1 you want to create a new matrix for each line and store them in a list of some kind. This is how you might do it:
List<?> matrices = new ArrayList<?>();
while ((smaLine = reader.readLine()) != null)
{
float[][] mat = new float[MATRIX_ROWS][MATRIX_COLUMNS];
String[] values = smaLine.split(", ");
for(int i = 0; i < values.length; i++)
{
float[] testC = float(split(values[i], " "));
for (int j = 0; j < testC.length; j++)
{
mat[j][i] = testC[j];
}
}
matrices.add(mat);
x = x+1;
}
Where is x used, by the way?
Swap your mat1[j][i] = testC[j] to mat1[i][j] = testC[j]

Printing letters in 2D arrays? First letter not showing

I'm hoping someone can answer this so I'll try to explain this well.
My goal is to generate a MAXIMUM of 3 unique vowels (AEIOU) on a line of 5 squares. I have made 25 squares using a 2D array (board[][]), but I want to do the first line first. Picture it like this:
Now, my problem is, whenever I try to generate random letters in my squares, the first letter doesn't show. For example I have E and O, O would only show in my squares, and not E. It's printing in my console, but not in my GUI.
Also, sometimes DUPLICATES of letters are showing. I don't know how to fix this :|
Here are the codes I've done so far:
String board[][] = new String[5][5];
String alphabet = "AEIOU";
int numArray[] = new int[5]; //where I can store random indices of alphabet
int finalIndex = 0;
int random = (int) (Math.random()*3) + 1; //random number of vowels to be generated
//this loop covers everything
for(int ctr = 0; ctr < random; ctr++) {
while(ctr != finalIndex) { //checks if there are any duplicates
int rand = (int) (Math.random()*4); //random position for the letter
numArray[ctr] = rand;
while(numArray[ctr] != numArray[finalIndex]) {
finalIndex++;
}
}
//finds the position of the letter in alphabet and converts it to String
char character = alphabet.charAt(numArray[ctr]);
String s = String.valueOf(character);
System.out.println(s);
//loop for putting the letters to the 2D array
for(int i = 0; i < board.length; i++) {
int gen = (int) (Math.random()*4); //random square for letter
for(int j = 0; j <= gen; j++) {
if(i == 0 && j < 5) { //row 1
board[i][gen] = s;
}
}
}
}
I decided not to put my GUI code anymore just to make things simpler.
Sorry I couldn't read what you had, so i tried this myself...
int rows = 5;
Character [] vowels = {'A','E','I','O','U'};
Character [][] board = new Character [vowels.length][rows];
for(int row = 0;row<rows;row++){
ArrayList<Character> tempVowels = new ArrayList<Character>(Arrays.asList(vowels));
int numVowPerLine = (int)Math.floor(Math.random()*4);
for(int j = 0;j<numVowPerLine;j++){
do{
int pos = (int)Math.floor(Math.random()*5);
if(board[row][pos] == null){
int temp = (int)Math.floor(Math.random()*tempVowels.size());
board[row][pos] = tempVowels.get(temp);
tempVowels.remove(temp);
break;
}
}while(true);
}
}

Categories