Well firstly, I'll show my code:
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int a = 0;
int b = 0;
System.out.println("Welcome to Mine Sweeper!");
a = promptUser(in, "What width of map would you like (3 - 20):", 3, 20);
b = promptUser(in, "What height of map would you like (3 - 20):", 3, 20);
char[][] map = new char[a][b];
eraseMap(new char[a][b]);
}
public static int promptUser(Scanner in, String prompt, int min, int max) {
int userInput;
System.out.println(prompt);
userInput = in.nextInt();
while (userInput < min || userInput > max) {
System.out.println("Expected a number from 3 to 20.");
userInput = in.nextInt();
}
return userInput;
}
public static void eraseMap(char[][] map) {
for (int i = 0; i < map.length; ++i) {
for (int j = 0; j < map.length; ++j) {
System.out.print(Config.UNSWEPT + " ");
}
System.out.println();
}
return;
}
Basically, I'm trying to create a simple minesweeper game but what this is doing is that it is not printing the game map only using the width, instead of the width + height. For example, if I input 3 as the width and 4 as the height, it would output:
. . .
. . .
. . .
How would I fix this?
Change
for (int j = 0; j < map.length; ++j) {
to
for (int j = 0; j < map[i].length; ++j) {
because i is the outer array map[i] is the inner one. Alternatively, since you don't access map, pass in width and height instead. Like,
public static void eraseMap(int width, int height) {
for (int i = 0; i < width; ++i) {
for (int j = 0; j < height; ++j) {
System.out.print(Config.UNSWEPT + " ");
}
System.out.println();
}
}
Instead of map.length, you can use map[i].length in your inner loop.
Related
The program below ask the user how many mines he wants to see on the field and then display the field with mines.
In next step I need to calculate how many mines are around each empty cell. And I know that I
need to check 8 cells if the cell is in the middle, 5 cells if the cell is in the side, and 3
cells if the cell is in the corner. If there are from 1 to 8 mines around the cell, I need to
output the number of mines instead of the symbol representing an empty cell.
import java.util.Scanner;
import java.util.Random;
public class Minesweeper {
char[][] minesweeper = new char[9][9];
Random randNum = new Random();
Scanner sc = new Scanner(System.in);
public Minesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
minesweeper[i][j] = '*';
}
}
}
public void printMinesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(minesweeper[i][j]);
}
System.out.println();
}
}
public void randomX() {
System.out.print("How many mines do you want on the field?: ");
int numberOfMines = sc.nextInt();
int i = 0;
while (i < numberOfMines) {
int x = randNum.nextInt(9);
int y = randNum.nextInt(9);
if (minesweeper[x][y] == '*') {
minesweeper[x][y] = 'X';
i++;
}
}
printMinesweeper();
}
}
You can do it like this:
import java.util.Random;
import java.util.Scanner;
public class Minesweeper {
public static void main(String[] args) {
Minesweeper minesweeper = new Minesweeper();
minesweeper.randomX();
minesweeper.printMinesweeper();
}
char[][] minesweeper = new char[9][9];
Random randNum = new Random();
Scanner sc = new Scanner(System.in);
public Minesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
minesweeper[i][j] = '*';
}
}
}
public void printMinesweeper() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(getCharAt(i, j));
}
System.out.println();
}
}
private String getCharAt(int i, int j) {
if (mineAt(i, j)) {
return "X";
}
int minesNear = countMinesNear(i, j);
return Integer.toString(minesNear);
}
private boolean mineAt(int i, int j) {
return minesweeper[i][j] == 'X';
}
private int countMinesNear(int i, int j) {
int mines = 0;
for (int x = -1; x <= 1; x++) {//near fields in x direction
for (int y = -1; y <= 1; y++) {//near fields in y direction
if (x + i >= 0 && x + i < minesweeper.length && y + j >= 0 && y + j < minesweeper.length) {//check whether the field exists
if (minesweeper[x+i][y+j] == 'X') {//check whether the field is a mine
mines++;
}
}
}
}
return mines;
}
public void randomX() {
System.out.print("How many mines do you want on the field?: ");
int numberOfMines = sc.nextInt();
int i = 0;
while (i < numberOfMines) {
int x = randNum.nextInt(9);
int y = randNum.nextInt(9);
if (minesweeper[x][y] == '*') {
minesweeper[x][y] = 'X';
i++;
}
}
printMinesweeper();
}
}
The countMinesNear(int, int) method check whether the field near exists (to prevent index errors on the edges) and counts the mines if the fields exist.
I want to traverse a 3*3 submatrix within a large 7*7 matrix starting position from (1,1) that is middle element (2nd row , 2nd column).
The corresponding submatrix of position (1,1) will be
[(0,1),(0,2),(0,3)]
[(1,1),(1,2),(1,3)]
[(2,1),(2,2),(2,3)]
Like this traversing will go on.. and next submatrix starting posiion will be (1,2)
[(0,2),(0,3),(0,4)]
[(1,2),(1,3),(1,4)]
[(2,2),(2,3),(2,4)]
My Code
static int i;
static int j;
static int g;
static int h;
static void submatrix(int p,int q,int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(p+","+q);
shiftmatrix(p,q,mat);
}
static void shiftmatrix(int p,int q,int[][] mat) {
int m,n;
int[][] d = new int[3][3];
for( m=0;m<3;m++) {
for( n=0;n<3;n++) {
p=m+(p-1);
q=n+q;
d[m][n]=mat[p][q];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for ( m = 0; m < 3; m++){
for ( n = 0; n < 3; n++){
System.out.print(d[m][n]+"\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] a = new int[7][7];
int[][] mat = new int[7][7];
for ( i = 0; i < 7; i++)
{
for ( j = 0; j < 7; j++){
Random rand = new Random();
a[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (i = 0; i < 7; i++){
for (j = 0; j < 7; j++){
mat[g][h]=a[i][j];
System.out.print(mat[g][h]+"\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (i=1;i<6;i++) {
for (j=1;j<5;j++) {
int p=i;
int q=j;
submatrix(p,q,mat);
}
}
}
}
while running this code getting error as
ArrayIndexOutOfBoundsException: -1
Please help
The IndexOutOfBoundsException in your code was from you calling p = m + (p - 1). You don't need to change the p and q variables within every iteration of the loop.
In addition, you had several unnecessary variables, and had some of them static, something you should avoid when you're only using them in a loop like this. After cleaning up the code's formatting and deleting all unnecessary variables I believe the code functions as you want it to.
The code ignores the first row and column of your random matrix. Is this desired behavior?
import java.util.Random;
public class MatrixTest {
public static void subMatrix(int startRow, int startCol, int[][] mat) {
System.out.print("Submatrix for : ");
System.out.println(startRow + ", " + startCol);
shiftMatrix(startRow, startCol, mat);
}
public static void shiftMatrix(int startRow, int startCol, int[][] mat) {
int[][] d = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
//to properly move within the 3x3 you only need to add a
//constant buffer to the indices of mat[][]
d[i][j] = mat[i + startRow][j + startCol];
}
}
System.out.println("Your 3*3 SubMatrix is : ");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(d[i][j] + "\t");
}
System.out.println();
}
}
public static void main(String[] args) {
int[][] mat = new int[7][7];
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++){
Random rand = new Random();
mat[i][j] = rand.nextInt(10);
}
}
//copying large matrix to another for passing by argument
System.out.println("Copied matrix is : ");
for (int i = 0; i < 7; i++){
for (int j = 0; j < 7; j++) {
System.out.print(mat[i][j] + "\t");
}
System.out.println();
}
//Here is the 3*3 submatrix traversing starts...
for (int i = 1; i < 5; i++) { //changed from i < 6 to i < 5 to stay inside 7x7
for (int j = 1; j < 5; j++) {
subMatrix(i, j, mat);
}
}
}
}
I'm trying to randomly place 1D string array into 2D char array but I'm having issues with my for-loop.
userWords is 1D array of String while puzzleBoard is a 2D array of char.
I've tried
for(int i=0; i<userWords.length;i++) {
puzzleBoard[r++] = userWords[i].toCharArray();
}
but it's not placing it randomly like I want it to
So I tried
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
but it's printing only 3 char instead of the 3 strings of char into the char array.
I've also tried
puzzleBoard[r][c] = userWords[i].toCharArray();
instead of
puzzleBoard[r][c] = userWords[i].charAt(i);
But it display error "cannot convert from char[] to char"
Thank you
Full Code
public static void main(String[] args) {
String[] userWords = new String[3];
Methods.userInput(userWords); //ask user for input
Methods.fillPuzzle(puzzleBoard); //fill the puzzle with random char
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
puzzleBoard[r][c] = userWords[i].charAt(i);
}
Methods.printPuzzle(puzzleBoard); //print out the puzzle
}//end main
public static void printPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
System.out.print(a[i][j] + " ");
}
System.out.print((i+1));
System.out.println();
}
}//end printPuzzle
public static void fillPuzzle(char a[][]) {
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
a[i][j] = '*';
}
}
}//end fillPuzzle
public static void userInput(String a[]) {
Scanner input = new Scanner(System.in);
for(int i = 0; i < a.length;i++) {
System.out.println((i+1) + ". enter word:");
a[i] = input.next().toUpperCase();
}
}//end userInput
You can try this one:
for (int i = 0; i < userWords.length; i++) {
int r = rand.nextInt(puzzleBoard.length);
int c = rand.nextInt(puzzleBoard[r].length - userWords[i].length());
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
And you should add something that detects whether there is already a word at this position, otherwise you would overwrite it if the random numbers point to a location where is already written a word.
I think you should use 2 for-loops because you want to select first the string and next the characters in the string.
for(int i=0; i<userWords.length;i++) {
int r = rand.nextInt(ROW) + 1;
int c = rand.nextInt(COLUMN) + 1;
for (int j = 0; j < userWords[i].length(); j++) {
puzzleBoard[r][c + j] = userWords[i].charAt(j);
}
}
The problem is when you entry an input with scanner ,it shows on console. I want them to shown in an order. I want them shown like a matris. But with nextInt method all shows bottom of each other.
I want a console output like this:
But with nextInt() method your new int shows on nextLine like this:
How can i show multiple variables in same line with scanner?
import java.util.Scanner;
public class ProbilityMatrixTest {
static int M;
static int N;
static float[][] matrixX;
static float[][] matrixY;
static boolean isProbilityMatrix;
public static void main(String[] args) {
initiate();
testMatrix(matrixX);
System.out.println();
multiplyMatrix();
testMatrix(matrixY);
}
public static void initiate() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the row and column size of matrix : ");
M = sc.nextInt();
N = sc.nextInt();
System.out.println();
matrixX = new float[M][N];
System.out.println("Enter values of " + M + "x" + N + " matrix :");
for (int j = 0; j < N; j++) {
for (int i = 0; i < M; i++) {
matrixX[i][j] = sc.nextFloat();
}
}
}
public static void testMatrix(float[][] givenMatrix) {
isProbilityMatrix = true;
if (M != N) {
isProbilityMatrix = false;
}
for (int j = 0; j < N; j++) {
float rowVariablesTotal = 0;
for (int i = 0; i < M; i++) {
rowVariablesTotal += givenMatrix[i][j];
if (givenMatrix[i][j] < 0) {
isProbilityMatrix = false;
}
}
if (rowVariablesTotal != 1.0f) {
isProbilityMatrix = false;
}
}
System.out.print("TEST RESULT : ");
if (isProbilityMatrix) {
System.out.println("Probility matrix");
} else {
System.out.println("not Probility matrix");
}
}
public static void multiplyMatrix() {
matrixY = new float[M][N];
for (int i = 0; i < M; i++) {
for (int j = 0; j < N; j++) {
float newMatrixVariable = 0;
for (int a = 0; a < M; a++) {
newMatrixVariable += (matrixX[i][a] * matrixX[a][j]);
}
matrixY[i][j] = newMatrixVariable;
}
}
System.out.println("The square of given matrix:");
for (int j = 0; j < M; j++) {
for (int i = 0; i < N; i++) {
System.out.print(matrixY[i][j] + " ");
}
System.out.println();
}
}
}
You need to scan entire lines at a time. Otherwise, you're always pressing the enter key, causing it to look like you're entering one value before the other on previous lines
For example, type 3 3, then enter, then you can type three space separated decimal values, enter, then repeat that twice
System.out.print("Enter the row and column size of matrix : ");
String[] mn = sc.nextLine().split("\\s+");
int M = Integer.parseInt(mn[0]);
int N = Integer.parseInt(mn[1]);
System.out.println();
double[][] matrixX = new double[N][];
for (int i = 0; i < N; i++) {
matrixX[i] = new double[M];
String[] row = sc.nextLine().split("\\s+");
for (int j = 0: j < M: j++) {
matrix[i][j] = Double.parseDouble(row[j]);
//...
}
}
My code needs to multiply each row of an array by each column of the next. The user inputs the height and width and the program will randomly generate the array values. It doesn't give any errors if the arrays are equal for example (3x3)(3x3) or even if you do (3x2)(2x3). if however you enter something like (3x3)(3x2) it gives an out of bounds exception.
public class Multiply {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int width = -1;
int height = 0;
int width2 = 0;
int height2 = 0;
while (width != height2) {
while (height <= 0) {
System.out.print("Enter a height for array1: ");
height = checkInt(scan);
}
while (width <= 0) {
System.out.print("Enter a width for array1: ");
width = checkInt(scan);
}
while (height2 <= 0) {
System.out.print("Enter a height for array2: ");
height2 = checkInt(scan);
}
while (width2 <= 0) {
System.out.print("Enter a width for array2: ");
width2 = checkInt(scan);
}
if (width != height2) {
System.out
.println("Error! Dimensions of matrices not compatible. Try again.");
width = -1;
height = 0;
width2 = 0;
height2 = 0;
}
}
int array1[][] = randomMatrix(height, width);
int array2[][] = randomMatrix(height2, width2);
int product[][] = matrixMultiply(array1, array2, height, width2);
printArray(product);
}// end of main method
public static int[][] randomMatrix(int height, int width) {
int array1[][] = new int[height][width];
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j++) {
array1[i][j] = (int) (-10 + Math.random() * 20);
}
}
return array1;
}// end of randomMatrix method
public static int[][] matrixMultiply(int[][] array1, int[][] array2, int height, int width) {
int[][] product = new int[height][width];
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1[i].length; j++) {
int prod = 0;
for (int k = 0; k < array2.length; k++) {
prod = prod + array1[i][k] * array2[k][j];
}
product[i][j] = prod;
}
}
return product;
}// end of matrixMultiply method
public static void printArray(int[][] array) {
System.out.println(" ");
System.out.println("Row Major Representation:");
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j] + " ");
}
System.out.println();
}
System.out.println(" ");
System.out.println("Column Major Representation:");
for (int i = 0; i < array[1].length; i++) {
for (int j = 0; j < array.length; j++) {
System.out.print(array[j][i] + " ");
}
System.out.println();
}
}
public static int checkInt(Scanner scan) {
int width = 0;
if (scan.hasNextInt()) {
width = scan.nextInt();
return width;
} else {
scan.next();
return 0;
}
}
}// end of public class Multiply
The value of the variable "j" (Line 82) in its final iteration is causing the Out of Bounds Exception. The error occurs for (3x3)(3x2) because in the final "j" iteration, j equals 2, making the value higher than 1 (the highest index value for j's location). Adding some logic to check for when j > the highest index will prevent the issue.