Trying to make battleship but String[][] board will not update properly - java

The userGuess[y, x] gets compared to ship1[][] but only updates the board[][] at the matching index with "!" when I enter a user guess that equals (ship1[2][0], ship1[2][1]).
In other words, I feed updateBoard() the int[] userGuess, updateBoard loops through the int[][] ship1 and compares userGuess[0] to ship1[0][0] and userGuess[1] to ship1[0][1]...ship1[2][0], ship1[2][1], looking to see if they match, but the only match I am getting is if I enter a userGuess that equals the values at (ship1[2][0], ship1[2][1]).
Does anyone see what I have done wrong?
package assignment_8;
import java.util.Scanner;
public class Battleship {
private String[][] board = new String[8][8];
private int[][] ship1 = new int[3][2];
private int[][] ship2 = new int[4][2];
private int counter;
Battleship() {
}
public void makeBoard() {
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[i].length; j++) {
board[i][j] = "| ";
board[i][7] = "| |";
}
}
}
public void makeShips() {
int ship1Y = (int)Math.floor(Math.random() * 7);
int ship1X = (int)Math.floor(Math.random() * 7);
int ship2Y = (int)Math.floor(Math.random() * 7);
int ship2X = (int)Math.floor(Math.random() * 7);
int coinToss = (int)Math.floor(Math.random() * 2) + 1;
if(coinToss == 1) {
if(ship1X >= 5) {
ship1X = 4;
}
for(int i = 0; i < ship1.length; i++) {
ship1[i][0] = ship1Y;
ship1[i][1] = ship1X + i;
}
if(ship2Y >= 4) {
ship2Y = 3;
}
for(int i = 0; i < ship2.length; i++) {
ship2[i][0] = ship2Y + i;
ship2[i][1] = ship2X;
}
} else {
if(ship1Y >= 5) {
ship1Y = 4;
}
for(int i = 0; i < ship1.length; i++) {
ship1[i][0] = ship1Y + i;
ship1[i][1] = ship1X;
}
if(ship2X >= 4) {
ship2X = 3;
}
for(int i = 0; i < ship2.length; i++) {
ship2[i][0] = ship2Y;
ship2[i][1] = ship2X + i;
}
}
}
public String[][] getBoard() {
return board;
}
public int[][] getShip1() {
return ship1;
}
public int[][] getShip2() {
return ship2;
}
public int getCounter() {
return counter;
}
public void updateBoard(int[] userInput) {
for(int i = 0; i < ship1.length; i++) {
if(ship1[i][0] == userInput[0] && ship1[i][1] == userInput[1] && board[userInput[0]][userInput[1]] == "| ") {
counter++;
} else if (ship1[i][0] == userInput[0] && ship1[i][1] == userInput[1] && board[userInput[0]][userInput[1]] == "| |") {
counter++;
}
if(ship1[i][0] == userInput[0] && ship1[i][1] == userInput[1]) {
board[userInput[0]][userInput[1]] = "|!";
if(userInput[1] == 7) {
board[userInput[0]][userInput[1]] = "|!|";
}
} else {
board[userInput[0]][userInput[1]] = "|X";
if(userInput[1] == 7) {
board[userInput[0]][userInput[1]] = "|X|";
}
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Battleship bs = new Battleship();
bs.makeBoard();
bs.makeShips();
int[][] ship1 = bs.getShip1();
//int[][] ship2 = bs.getShip2();
for(int i = 0; i < ship1.length; i++) {
System.out.println("[" + ship1[i][0] + "][" + ship1[i][1] + "]");
}
System.out.println();
/*for(int i = 0; i < ship2.length; i++) {
System.out.println("[" + ship2[i][0] + "][" + ship2[i][1] + "]");
}*/
System.out.println();
int[] userGuess = new int[2];
int counter = 0;
String[][] board = bs.getBoard();
do {
for(int i = 0; i < board.length; i++) {
for(int j = 0; j < board[i].length; j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
counter = bs.getCounter();
System.out.println("Counter = " + counter);
System.out.print("Enter Y coordinate (0 - 7): ");
userGuess[0] = sc.nextInt();
System.out.print("Enter X coordinate(0 - 7): ");
userGuess[1] = sc.nextInt();
bs.updateBoard(userGuess);
System.out.println();
} while(counter < 8);
}
}

The issue is with the following condition check:
if(ship1[i][0] == userInput[0] && ship1[i][1] == userInput[1]) {
board[userInput[0]][userInput[1]] = "|!";
if(userInput[1] == 7) {
board[userInput[0]][userInput[1]] = "|!|";
}
} else {
board[userInput[0]][userInput[1]] = "|X";
if(userInput[1] == 7) {
board[userInput[0]][userInput[1]] = "|X|";
}
}
If the user gives co-ordinates that match with ship1[0][0] and ship[0][1], it assigns ! to it but the loop continues and next two ship1 array values won't match thereby resetting it to X
The fix is to break out of the loop when the match is found.
if(ship1[i][0] == userInput[0] && ship1[i][1] == userInput[1]) {
board[userInput[0]][userInput[1]] = "|!";
if(userInput[1] == 7) {
board[userInput[0]][userInput[1]] = "|!|";
}
break; // that's it!
}

Related

Minimax algorithm for Tic Tac Toe not working

I am attempting to make an unbeatable Tic Tac Toe game using a simplified minimax algorithm. The code looks like this:
private static int findBestMove(String[][] board, boolean comp) {
// comp returns true if the computer is the one looking for the best move
// findBestMove is always called by the program as findBestMove(board, true)
// since the computer is the only one that uses it
// If the board in its current state is a win for the
// player, return -1 to indicate a loss
if (playerWon(board)) return -1;
// If the board in its current state is a win for the
// computer, return 1 to indicate a win
if (compWon(board)) return 1;
// If the board in its current state is a tie
// return 0 to indicate a tie
if (tie(board)) return 0;
// Set the default possible outcome as the opposite of what
// the respective player wants
int bestPossibleOutcome = comp ? -1 : 1;
// Loop through the board looking for empty spaces
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
// Once an empty space is found, create a copy of the board
// with that space occupied by the respective player
if (board[i][j].equals(" ")) {
String[][] newBoard = new String[3][3];
for (int a = 0; a < 3; a++) {
System.arraycopy(board[a], 0, newBoard[a], 0, 3);
}
newBoard[i][j] = comp ? "O" : "X";
// Recursively call findBestMove() on this copy
// and see what the outcome is
int outCome = findBestMove(newBoard, !comp);
// If this is the computer's turn, and the outcome
// is higher than the value currently stored as the
// best, replace it
if (comp && outCome > bestPossibleOutcome) {
bestPossibleOutcome = outCome;
// r and c are instance variables that store the row
// and column of what the computer's next move should be
r = i;
c = j;
// If this is the player's turn, and the outcome
// is lower than the value currently stored as the
// best, replace it
} else if (!comp && outCome < bestPossibleOutcome) {
bestPossibleOutcome = outCome;
}
}
}
}
// Return the ultimate value deemed to be the best
return bestPossibleOutcome;
}
The idea is that after I run this program, the instance variables r and c should contain the row and column, respectively, of the computer's best move. However, the program only successfully prevents a loss about half the time, and I can't tell if the other half is luck, or if the program is actually working.
I am aware that the computer will respond to every scenario exactly the same way each game. That is fine.
In the event anyone would like to run the program, I have included the full class below:
import java.util.Scanner;
public class TicTacToe {
private static int r;
private static int c;
private static void printBoard(String[][] board) {
System.out.println(" 0 1 2");
System.out.println("0 " + board[0][0] + " | " + board[0][1] + " | " + board[0][2] + " ");
System.out.println(" ---+---+---");
System.out.println("1 " + board[1][0] + " | " + board[1][1] + " | " + board[1][2] + " ");
System.out.println(" ---+---+---");
System.out.println("2 " + board[2][0] + " | " + board[2][1] + " | " + board[2][2] + " ");
}
private static boolean playerWon(String[][] board) {
return playerHasThreeInCol(board) || playerHasThreeInDiag(board) || playerHasThreeInRow(board);
}
private static boolean playerHasThreeInRow(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2]) && board[i][0].equals("X")) return true;
}
return false;
}
private static boolean playerHasThreeInCol(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]) && board[0][i].equals("X")) return true;
}
return false;
}
private static boolean playerHasThreeInDiag(String[][] board) {
if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]) && board[0][0].equals("X")) return true;
return board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]) && board[0][2].equals("X");
}
private static boolean compWon(String[][] board) {
return compHasThreeInCol(board) || compHasThreeInDiag(board) || compHasThreeInRow(board);
}
private static boolean compHasThreeInRow(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[i][0].equals(board[i][1]) && board[i][0].equals(board[i][2]) && board[i][0].equals("O")) return true;
}
return false;
}
private static boolean compHasThreeInCol(String[][] board) {
for (int i = 0; i < 3; i++) {
if (board[0][i].equals(board[1][i]) && board[0][i].equals(board[2][i]) && board[0][i].equals("O")) return true;
}
return false;
}
private static boolean compHasThreeInDiag(String[][] board) {
if (board[0][0].equals(board[1][1]) && board[0][0].equals(board[2][2]) && board[0][0].equals("O")) return true;
return board[0][2].equals(board[1][1]) && board[0][2].equals(board[2][0]) && board[0][2].equals("O");
}
private static boolean tie(String[][] board) {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) return false;
}
}
return true;
}
private static int findBestMove(String[][] board, boolean comp) {
if (playerWon(board)) return -1;
if (compWon(board)) return 1;
if (tie(board)) return 0;
int bestPossibleOutcome = comp ? -1 : 1;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
String[][] newBoard = new String[3][3];
for (int a = 0; a < 3; a++) {
System.arraycopy(board[a], 0, newBoard[a], 0, 3);
}
newBoard[i][j] = comp ? "O" : "X";
int outCome = findBestMove(newBoard, !comp);
if (comp && outCome > bestPossibleOutcome) {
bestPossibleOutcome = outCome;
r = i;
c = j;
} else if (!comp && outCome < bestPossibleOutcome) {
bestPossibleOutcome = outCome;
}
}
}
}
return bestPossibleOutcome;
}
private static void go() {
Scanner input = new Scanner(System.in);
String[][] board = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
board[i][j] = " ";
}
}
printBoard(board);
for (int i = 0;; i++) {
if (i % 2 == 0) {
while (true) {
System.out.println("Enter position: ");
String position = input.nextLine();
int row, column;
try {
row = Integer.parseInt(position.substring(0, 1));
column = Integer.parseInt(position.substring(1, 2));
} catch (Exception e) {
System.out.println("Invalid entry. ");
continue;
}
if (row < 0 || row > 2 || column < 0 || column > 2) {
System.out.println("That position is not on the board. ");
continue;
}
if (!board[row][column].equals(" ")) {
System.out.println("That space is already taken. ");
continue;
}
board[row][column] = "X";
break;
}
} else {
System.out.println("\nMy move: ");
findBestMove(board, true);
board[r][c] = "O";
}
printBoard(board);
if (playerWon(board)) {
System.out.println("You win!");
break;
} else if (compWon(board)) {
System.out.println("I win!");
break;
} else if (tie(board)) {
System.out.println("Tie game");
break;
}
}
}
public static void main(String[] args) {
go();
}
}
I'm not asking for anyone to rewrite the whole thing for me, but if you can point out any obvious mistakes or point me in the right direction, that would be appreciated. I am also open to any suggestions or comments that you may have.
I haven't extensively tested it yet, but I believe that I resolved the issue. The new code looks like this:
private static void findBestMove(String[][] board) {
double bestMove = Double.NEGATIVE_INFINITY;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
board[i][j] = "O";
double score = minimax(board, false);
board[i][j] = " ";
if (score > bestMove) {
bestMove = score;
r = i;
c = j;
}
}
}
}
}
private static double minimax(String[][] board, boolean comp) {
if (playerWon(board)) {
return -1;
}
if (compWon(board)) {
return 1;
}
if (tie(board)) return 0;
double bestScore;
if (comp) {
bestScore = Double.NEGATIVE_INFINITY;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
board[i][j] = "O";
double score = minimax(board, false);
board[i][j] = " ";
bestScore = Math.max(score, bestScore);
}
}
}
} else {
bestScore = Double.POSITIVE_INFINITY;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (board[i][j].equals(" ")) {
board[i][j] = "X";
double score = minimax(board, true);
board[i][j] = " ";
bestScore = Math.min(score, bestScore);
}
}
}
}
return bestScore;
}
I abstracted the minimax algorithm away from the next move coordinate setter, which I think may have made a difference. Otherwise, it is very similar.

Print a message only once after iterating 2d array

import java.util.Scanner;
public class Note {
public static void main(String[] args) {
String etudiants[][] = new String[1][4];
Scanner saisie = new Scanner(System.in);
for (int i = 0; i < 1; i++) {
System.out.print("\n\nEtudiant BTI00" + (i + 1) + "\n\n");
for (int j = 0; j < 4; j++) {
if (j == 0) {
System.out.print("\n\tCode de l'etudiant : ");
} else if (j == 1) {
System.out.print("\n\tNom etudiant : ");
} else if (j == 2) {
System.out.print("\n\tNote Maths : ");
} else if (j == 3) {
System.out.print("\n\tNote Francais : ");
} else {
System.out.print("\n\tChamps inexistant!");
}
etudiants[i][j] = saisie.nextLine();
}
}
System.out.print("\n\tEtudiants Enregistres : \n\n");
// System.out.print("\tCode\tNom\t\tMaths\tFrancais\n\n");
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 4; j++) {
System.out.print("\t" + etudiants[i][j] + " ");
}
}
System.out.println();
System.out.print("\n\tEntrez code etudiant : ");
String recherche = saisie.nextLine();
boolean trouve = false;
for (int i = 0; i < 1; i++) {
for (int j = 0; j < 4; j++) {
if (recherche.equals(etudiants[i][0])) {
trouve = true;
System.out.print("\n\tCode etudiant correct!");
String math = etudiants[i][2];
String francais = etudiants[i][3];
Double m = new Double(math);
double mathConv = m.doubleValue();
Double f = new Double(francais);
double francaisConv = f.doubleValue();
double moyenne = (mathConv + francaisConv) / 2;
System.out.print("\n\tMoyenne de l'etudiant : " + moyenne);
System.out.print("\n\tEtudiant : " + etudiants[i][j]);
if (moyenne <= 40) {
System.out.print("\n\tEchec!");
} else if (moyenne > 40 && moyenne < 70) {
System.out.print("\n\tReprise!");
} else {
System.out.print("\n\tSucces!");
}
} if (!trouve) {
System.out.print("\n\tCode etudiant incorrect!");
}
}
}
}
}
I need to display only one message after entering the code etudiant but istead it displays the message 4 times. The loop should only iterate through the first column of each line and compares it to what the user entered.
The indexing variable (j) of the last inner for-loop (for (int j = 0; j < 4; j++) {) is never used inside the loop, so you actually do not need that loop at all. General styling issues of your sample aside, you should rewrite the last loop like this:
for (int i = 0; i < 1; i++) {
// throw away this
//for (int j = 0; j < 4; j++) {
if (recherche.equals(etudiants[i][0])) {
trouve = true;
// ... rest of the code like you currently have it
// You probably do not need this line too,
// because you have almost the same in your second loop
//System.out.print("\n\tEtudiant : " + etudiants[i][j]);
}
}

Can someone help me with my win scenario in my Gomoku program?

I have written a program for an assignment where we had to write a simple Gomoku program. I thought I had it all, but when I compile and run, it sets off the win scenario even if I only have 4 of a kind and even if they're not next to each other. (It should only set off a win if there are five in a row of one kind...X's or O's). I feel like I should be resetting my counter back to 0 before each turn, but I'm not sure where I should be doing that. Any tips would be appreciated!
import java.util.Scanner;
public class Gomoku1
{
public static void main (String[] args)
{
Scanner input = new Scanner(System.in);
char[][] map = new char [19][19];
int row = 0;
int column = 0;
//fill game with dots
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map[i].length; j++)
{
map[i][j] = '.';
}
}
printMap(map);
char player1Choice = 'X';
char player2Choice = 'O';
int [] place;
while (true)
{
System.out.println("Player 1's turn!");
place = userTurn(map, player1Choice);
if (isValidMove(map, place[0], place[1]) == false)
{
System.out.println("Invalid move! Try again!");
place = userTurn(map, player1Choice);
}
if (isValidMove(map, place[0], place[1])) {
map[place[0]][place[1]] = player1Choice;
printMap(map);
}
if (isBoardFull(map) == true)
{
System.out.println("Board is full. Tied game.");
break;
}
if (hasPlayerWon(map, player1Choice) == true)
{
System.out.println("Player 1 Wins!");
break;
}
else
{
System.out.println("Player 2's turn!: ");
place = userTurn(map, player2Choice);
//System.out.println(isValidMove(map, row, column));
if (isValidMove(map, place[0], place[1]) == false)
{
System.out.println("Invalid move! Try again!");
place = userTurn(map, player2Choice);
}
if (isValidMove(map, place[0], place[1])) {
map[place[0]][place[1]] = player2Choice;
printMap(map);
}
if (isBoardFull(map) == true)
{
System.out.println("Board is full. Tied game.");
break;
}
if (hasPlayerWon(map, player2Choice) == true)
{
System.out.println("Player 2 Wins!");
break;
}
}
}
}
public static void printMap (char[][] map)
{
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map[i].length; j++)
{
System.out.printf("%2c", map[i][j]);
}
System.out.println();
}
}
public static int [] userTurn (char[][] map, char playerChoice)
{
Scanner input = new Scanner(System.in);
System.out.print("Enter row: ");
int row = input.nextInt();
System.out.print("Enter column: ");
int column = input.nextInt();
int place [] = {row, column};
return place;
}
public static boolean isValidMove (char[][] map, int row, int column)
{
//System.out.println ("n is valid move");
if (row < 0 || row > 18 || column < 0 || column > 18 || map[row][column]=='O' || map[row][column]=='X')
{
return false;
}
else
{
return true;
}
}
public static boolean isBoardFull (char[][] map)
{
int openSpots = 0;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (!(map[i][j]=='.'))
openSpots++;
}
}
if (openSpots == 361)
{
return true;
}
return false;
}
public static boolean hasPlayerWon(char[][] map, int player)
{
if (isHorizontalWin(map, player) == true || isVerticalWin(map, player) == true || isDiagonalWin(map, player) == true)
{
return true;
}
return false;
}
public static boolean isHorizontalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 0;
c += 1;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
public static boolean isVerticalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 1;
c += 0;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
public static boolean isDiagonalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count++;
r += 1;
c += 1;
}
}
}
}
if (count == 5)
{
return true;
}
return false;
}
}
You have problems in all three of the function that check win conditions: isHorizontalWin, isVerticalWin, and isDiagonalWin. All three increment the variable count, but this variable is never set back to zero. Additionally, the check to see if count == 5 should be made inside the loop. Here is an example on how to fix isHorizontalWin:
public static boolean isHorizontalWin(char[][] map, int player)
{
int count = 0;
int r;
int c;
for (int i = 0; i < map.length; i++)
{
for (int j = 0; j < map.length; j++)
{
if (map[i][j]==(player))
{
r = i;
c = j;
while (r >= 0 && r <= 18 && c >= 0 && c <= 18 && map[r][c] == player)
{
count ++;
r += 0;
c += 1;
}
if (count == 5)
{
return true;
} else {
count = 0;
}
}
}
}
return false;
}

Libgdx Generate RogueLIke Dungeon - Algorithm Error

I have used Libgdx to generate a dungeon out of keyboard characters. I have decided to print out the array as a text file.
However this is what I got:
Furthermore, It isn't consistent
I don't get what is wrong?
I checked over my algorithm and didn't find anything wrong.
Here is my code:
public class test1 extends ApplicationAdapter {
SpriteBatch batch;
Texture img;
int X = 50;
int Y = 25;
////////// # wall
////////// . ground
char[][][] mapChars = new char[1000][1000][1000];
private void genDung() {
int clearance = 4;
for (int i = 0; i < Y; i++) {
for (int j = 0; j <= X; j++) {
if(j == X)
mapChars[0][i][j] = '\n';
else
mapChars[0][i][j] = '#';
}
}
int roomCount = MathUtils.random(2, 2);
int[] roomPosX = new int[roomCount];
int[] roomPosY = new int[roomCount];
int[] roomCenterPosX = new int[roomCount];
int[] roomCenterPosY = new int[roomCount];
int[] roomSizeX = new int[roomCount];
int[] roomSizeY = new int[roomCount];
for (int i = 0; i < roomCount; i++) {
int attempts = 0;
while(true) {
boolean rePosition = false;
roomPosX[i] = MathUtils.random(1, X-1);
roomPosY[i] = MathUtils.random(1, Y-1);
roomSizeX[i] = MathUtils.random(2, 12);
roomSizeY[i] = MathUtils.random(2, 8);
for(int j = 0; j <= i; j++) {
if(i != j) {
if(roomPosX[i] >= roomPosX[j] && roomPosX[i] <= (roomPosX[j] + roomSizeX[j] + clearance)) {
if(roomPosY[i] >= roomPosY[j] && roomPosY[i] <= (roomPosY[j] + roomSizeY[j] + clearance)) {
rePosition = true;
break;
}
}
if((roomPosX[i]+roomSizeX[i]) >= roomPosX[j] && (roomPosX[i]+roomSizeX[i]) <= (roomPosX[j] + roomSizeX[j] + clearance)) {
if((roomPosY[i]+roomSizeY[i]) >= roomPosY[j] && (roomPosY[i]+roomSizeY[i]) <= (roomPosY[j] + roomSizeY[j] + clearance)) {
rePosition = true;
break;
}
}
if((roomPosX[i]) >= roomPosX[j] && (roomPosX[i]) <= (roomPosX[j] + roomSizeX[j] + clearance)) {
if((roomPosY[i]+roomSizeY[i]) >= roomPosY[j] && (roomPosY[i]+roomSizeY[i]) <= (roomPosY[j] + roomSizeY[j] + clearance)) {
rePosition = true;
break;
}
}
if((roomPosX[i]+roomSizeX[i]) >= roomPosX[j] && (roomPosX[i]+roomSizeX[i]) <= (roomPosX[j] + roomSizeX[j] + clearance)) {
if((roomPosY[i]) >= roomPosY[j] && (roomPosY[i]) <= (roomPosY[j] + roomSizeY[j] + clearance)) {
rePosition = true;
break;
}
}
}
else if(roomPosX[j] + roomSizeX[j] >= X-1){
rePosition = true;
}
else if(roomPosY[j] + roomSizeY[j] >= Y-1){
rePosition = true;
}
}
attempts++;
if(attempts >= 10000) break;
if(!rePosition) break;
}
}
for(int r = 0; r < roomCount; r++) {
for (int a = roomPosX[r]; a <= (roomPosX[r] + roomSizeX[r]); a++) {
for (int b = roomPosY[r]; b <= (roomPosY[r] + roomSizeY[r]); b++) {
mapChars[0][b][a] = '.';
}
}
}
Gdx.app.log("roomCount", String.valueOf(roomCount)+"\n\n\n");
for(int i =0; i< roomCount; i++) {
roomCenterPosX[i] = roomPosX[i] + roomSizeX[i]/2;
roomCenterPosY[i] = roomPosY[i] + roomSizeY[i]/2;
Gdx.app.log("room", String.valueOf(i)+"\n");
Gdx.app.log("roomPosX", String.valueOf(roomPosX[i]));
Gdx.app.log("roomPosY", String.valueOf(roomPosY[i]));
Gdx.app.log("roomSizeX", String.valueOf(roomSizeX[i]));
Gdx.app.log("roomSizeY", String.valueOf(roomSizeY[i])+"\n");
Gdx.app.log("RoomCenterPosX", String.valueOf(roomCenterPosX[i]));
Gdx.app.log("RoomCenterPosY", String.valueOf(roomCenterPosY[i])+"\n\n");
}
int difference = X;
int[] roomNum = new int[2];
for(int i = 0; i < roomCount; i++) {
for(int j = 0; j < roomCount; j++) {
if(i != j) {
if(abs(roomCenterPosX[i] - roomCenterPosX[j]) < difference) {
difference = abs(roomCenterPosX[i] - roomCenterPosX[j]);
roomNum[0] = i;
roomNum[1] = j;
}
}
}
}
Gdx.app.log("FarthestRooms", String.valueOf(roomNum[0]));
Gdx.app.log("FarthestRooms", String.valueOf(roomNum[1]));
int differenceX = X;
int differenceY = Y;
int[] connectRooms = new int[2];
// int[] roomsConnected = new int[roomCount];
connectRooms[0] = MathUtils.random(0, roomCount - 1);
// roomsConnected[0] = connectRooms[0];
int count;
for(int i = 0; i < roomCount-1; i++) {
int j;
while(true) {
connectRooms[1] = MathUtils.random(0, roomCount - 1);
/* while (true) {
connectRooms[1] = MathUtils.random(0, roomCount - 1);
count = 0;
for (j = 0; j < i; j++) {
if (connectRooms[1] != roomsConnected[j] && connectRooms[0] != roomsConnected[j]){
count++;
}
}
if(count >= i-2)
break;
}*/
if(connectRooms[0] != connectRooms[1])
break;
}
// roomsConnected[i+1] = connectRooms[1];
differenceX = roomCenterPosX[connectRooms[0]] - roomCenterPosX[connectRooms[1]];
differenceY = roomCenterPosY[connectRooms[0]] - roomCenterPosY[connectRooms[1]];
if(roomCenterPosX[connectRooms[0]] < roomCenterPosX[connectRooms[1]])
differenceX *= -1;
if(roomCenterPosY[connectRooms[0]] < roomCenterPosY[connectRooms[1]])
differenceY *= -1;
int k;
try {
if (differenceX > 0) {
for (k = 0; k < differenceX; k++) {
mapChars[0][roomCenterPosY[i]][roomCenterPosX[i] + k] = '.';
}
} else if (differenceX < 0) {
for (k = 0; k > differenceX; k--) {
mapChars[0][roomCenterPosY[i]][roomCenterPosX[i] + k] = '.';
}
} else k = 0;
if (differenceY < 0) {
for (int z = 0; z > differenceY; z--) {
mapChars[0][roomCenterPosY[i] + z][roomCenterPosX[i] + k] = '.';
}
} else if (differenceY > 0) {
for (int z = 0; z < differenceY; z++) {
mapChars[0][roomCenterPosY[i] + z][roomCenterPosX[i] + k] = '.';
}
} else {
}
}
catch (ArrayIndexOutOfBoundsException e) {
Gdx.app.log("Non Fatal Exception", String.valueOf(e));
}
Gdx.app.log("Connect", String.valueOf(connectRooms[0]));
Gdx.app.log("Connect", String.valueOf(connectRooms[1]));
Gdx.app.log("DifferenceX", String.valueOf(differenceX));
Gdx.app.log("DifferenceY", String.valueOf(differenceY)+"\n");
}
for(int q = 0; q < Y; q++) {
mapChars[0][q][X] = '\n';
}
for(int w = 0; w < Y; w++) {
mapChars[0][w][X-1] = '#';
}
for(int e = 0; e < Y; e++) {
mapChars[0][Y-1][e] = '#';
}
}
private void export() {
if(Gdx.files.isLocalStorageAvailable()) {
FileHandle fileHandle = Gdx.files.local("map.txt");
if(Gdx.files.local("map.txt").exists())
fileHandle.writeString("", false);
for(int i = 0; i<= Y; i++) {
for (int j = 0; j <= X; j++) {
fileHandle.writeString(""+mapChars[0][i][j] , true);
}
}
}
}
#Override
public void create () {
batch = new SpriteBatch();
img = new Texture("badlogic.jpg");
// genMap();
// for(int i = 0; i< 4; i++)
// refineMap();
genDung();
export();
}
#Override
public void render () {
Gdx.gl.glClearColor(0, 0, 0, 1);
Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
batch.begin();
batch.draw(img, 0, 0);
batch.end();
if(Gdx.input.isTouched()) {
// genMap();
// for(int i = 0; i< 4; i++)
// refineMap();
genDung();
export();
}
}
}
I want the two rooms to connect properly every time.
As you can see, one of the time, the rooms connected
The other time the rooms don't connect.
Thanks in advance
The whole thing can be simplified and definitely needs refactoring. Regarding the 2 room connection - check this piece carefully
differenceX = roomCenterPosX[connectRooms[0]] - roomCenterPosX[connectRooms[1]];
differenceY = roomCenterPosY[connectRooms[0]] - roomCenterPosY[connectRooms[1]];
if(roomCenterPosX[connectRooms[0]] < roomCenterPosX[connectRooms[1]])
differenceX *= -1;
if(roomCenterPosY[connectRooms[0]] < roomCenterPosY[connectRooms[1]])
differenceY *= -1;
As #kiheru pointed out it is equivalent to Math.abs(roomCenterPosX[connectRooms[0]] - roomCenterPosX[connectRooms[1]]) (same for Y). So you always "dig" to right and down, never up or left.
Drop that invertion and have fun with the rest of your algorithm :)

Scanner.nextInt() Returns null

Edit: Yes, I know that ScanObj is not a proper name. And here is all of my code. It is not complete so there are some errors and some glitches, but you asked for it:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.Scanner;
import javax.swing.JFrame;
public class MainClass {
static String[][] medium = new String[5][4];
static String names[] = { "Gatz ", "Cat ", "Women", "Mice ", "Robin",
"Romeo ", "Summer ", "Tempest", "Hamlet ", "Lear ",
"Titanic ", "StarWars", "DieHard ", "Elf ", "RED " };
static String lexile[] = { "L:1070", "L:123 ", "L:9254", "L:1234",
"L:534 ", "L:349", "L:632 ", "L:1097", "L:6453", "L:812 ",
"L:NA ", "L:NA ", "L:NA ", "L:NA ", "L:NA ", "L:NA " };
static String grade[] = { "G:9", "G:10", "G:12", "G:11", "G:9", "G:12",
"G:11", "G:9", "G:9", "G:12", "G:12", "G:11", "G:11", "G9", "G:9" };
static int max = 4;
char sorttype = (Character) null;
public static void main(String args[]) throws InterruptedException {
System.
out.println("Would you like to browse:\nB)Book C)CD or D)DVD");
Scanner ScanObj =
new Scanner(System.in);
String[] input =
new String[10];
input[1] = ScanObj.nextLine();
int store[] = { 6, 6, 6, 6, 6, 6 };
if (input[1].equals("B") || input[1].equals("Book")
|| input[1].equals(
"book") || input[1].equals("b")) {
String temp[][] =
new String[5][4];
int random[] = new int[5];
boolean repeat = true;
int nums[] = new int[5];
for (int i = 0; i < 5; i++) {
temp[i][0] =
"book";
temp[i][1] =
names[i];
temp[i][2] =
lexile[i];
temp[i][3] =
grade[i];
for (int qwop = 0; qwop < 4; qwop++) {
medium[i][qwop] = temp[i][qwop];
if (qwop == 0)
System.
out.printf(i + 1 + " | ");
else if (qwop < 3)
System.
out.printf(medium[i][qwop] + " | ");
else
System.
out.println(medium[i][qwop] + "\n");
Thread.sleep(150);
}
// System.out.println(temp[i][i]);
// random = store[i];
if (i == 4)
System.
out.printf("\n\n\n");
}
}
if (input[1].equals("C") || input[1].equals("c")
|| input[1].equalsIgnoreCase(
"CD") || input[1].equals("cd")) {
String temp[][] =
new String[5][4];
for (int i = 0; i < 5; i++) {
int random1 = (int) (Math.random() * max) + 6;
for (int p = 0; p < 4; p++) {
for (random1 = (int) (Math.random() * max) + 6; random1 == store[p];) {
random1 = (
int) (Math.random() * max) + 6;
}
}
temp[i][0] =
"CD";
temp[i][1] =
names[i + 5];
temp[i][2] =
lexile[i + 5];
temp[i][3] =
grade[i + 5];
for (int qwop = 0; qwop < 4; qwop++) {
medium[i][qwop] = temp[i][qwop];
if (qwop < 3)
System.
out.printf(medium[i][qwop] + " | ");
else
System.
out.println(medium[i][qwop] + "\n");
Thread.sleep(150);
}
// System.out.println(temp[i][i]);
random1 = store[i];
if (i == 4)
System.
out.printf("\n\n\n");
}
}
if (input[1].equalsIgnoreCase("D") || input[1].equalsIgnoreCase("DVD")) {
String temp[][] =
new String[5][4];
for (int i = 0; i < 5; i++) {
int random1 = (int) (Math.random() * max) + 6;
for (int p = 0; p < 4; p++) {
for (random1 = (int) (Math.random() * max) + 6; random1 == store[p];) {
random1 = (
int) (Math.random() * max) + 6;
}
}
temp[i][0] =
"DVD";
temp[i][1] =
names[i + 10];
temp[i][2] =
lexile[i + 10];
temp[i][3] =
grade[i + 10];
for (int qwop = 0; qwop < 4; qwop++) {
medium[i][qwop] = temp[i][qwop];
if (qwop < 3)
System.
out.printf(medium[i][qwop] + " | ");
else
System.
out.println(medium[i][qwop] + "\n");
Thread.sleep(150);
}
// System.out.println(temp[i][i]);
random1 = store[i];
if (i == 4)
System.
out.printf("\n\n\n");
}
}
// for loop goes through each of the parameters and compltes the
// instructions
System.
out
.println(
"How would you like to sort?\nA)Name B) Lexile C) Grade Level");
input[2] = ScanObj.nextLine();
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 2; j++) {
// if statement checks if the condition is true, then does the
// instructions if it is
// compareTo checks the ascii values of two strings. If the
// second
// is smaller (would come first in alphabetic order) it returns
// -1
boolean mismatch = true;
while (mismatch) {
if (input[2].equalsIgnoreCase("a")) {
mismatch =
false;
// makes a new temporary String
String temp1 =
null;
// Switches the String at position i with the one above
// it
for (int z = 0; z < medium.length - 1; z++) {
for (int x = z + 1; x < medium.length; x++) {
if (medium[z][1].compareTo(medium[x][1]) > 0) {
for (int qwop = 0; qwop < 4; qwop++) {
temp1 =
medium[z][qwop];
medium[z][qwop] = medium[x][qwop];
medium[x][qwop] = temp1;
}
mismatch =
true;
}
}
}
}
if (input[2].equalsIgnoreCase("b")) {
mismatch =
false;
// makes a new temporary String
String temp3 =
null;
// Switches the String at position i with the one above
// it
for (int z = 0; z < medium.length - 1; z++) {
for (int x = z + 1; x < medium.length; x++) {
if (medium[z][2].compareTo(medium[x][2]) > 0) {
for (int qwop = 0; qwop < 4; qwop++) {
temp3 =
medium[z][qwop];
medium[z][qwop] = medium[x][qwop];
medium[x][qwop] = temp3;
}
mismatch =
true;
}
}
}
}
if (input[2].equalsIgnoreCase("c")) {
mismatch =
false;
// makes a new temporary String
String temp3 =
null;
// Switches the String at position i with the one above
// it
for (int z = 0; z < medium.length - 1; z++) {
for (int x = z + 1; x < medium.length; x++) {
// Here I encounter an error because compareTo()
// sorts Lexicographically, meaning anything
// starting with a 1 comes before anything
// starting with a 2, 3, etc. This means that
// Grade 11 comes before grade 9, and simply
// comparing greater than does not work due to
// the fact that they are Strings.
if (medium[z][3].compareTo(medium[x][3]) > 0) {
for (int qwop = 0; qwop < 4; qwop++) {
temp3 =
medium[z][qwop];
medium[z][qwop] = medium[x][qwop];
medium[x][qwop] = temp3;
}
mismatch =
true;
}
}
}
}
}
}
}
Thread.sleep(1000);
for (int prt = 0; prt < medium.length; prt++) {
for (int qwop = 0; qwop < 4; qwop++) {
if (qwop < 3)
System.
out.printf(medium[prt][qwop] + " | ");
else
System.
out.println(medium[prt][qwop]);
}
}
Thread.sleep(1800);
for (int t = 0; t < 1000; t++) {
System.
out.println("\n\n\nTo edit a selection, type edit\n"
+
"To sort by a different category, type sort\n"
+
"To browse another medium, type browse\n"
+
"To search the " + medium[1][0] + "s, type search");
input[3] = ScanObj.nextLine();
if (input[3].equalsIgnoreCase("browse")) {
Thread.sleep(500);
System.out.println("What would you like to browse?:");
if (medium[1][0].equals("book")) {
System.out.println("CDs, or DVDs");
input[4] = ScanObj.nextLine();
}
if (medium[1][0].equals("CD")) {
System.out.println("Books, or DVDs");
input[4] = ScanObj.nextLine();
}
if (medium[1][0].equals("DVD")) {
System.out.println("Books, or CDs");
input[4] = ScanObj.nextLine();
}
if (input[4].equalsIgnoreCase("CD")
|| input[4].equalsIgnoreCase("DVD")
|| input[4].equalsIgnoreCase("Book")) {
for (int i = 0; i < 5; i++) {
String temp[][] = new String[5][4];
temp[i][0] =
"CD";
int addon = 0;
if (input[4].equals("CD"))
addon = 5;
if (input[4].equals("DVD"))
addon = 10;
temp[i][1] =
names[i + addon];
temp[i][2] =
lexile[i + addon];
temp[i][3] =
grade[i + addon];
for (int qwop = 0; qwop < 4; qwop++) {
medium[i][qwop] = temp[i][qwop];
if (qwop < 3)
System.
out.printf(medium[i][qwop] + " | ");
else
System.
out.println(medium[i][qwop] + "\n");
Thread.sleep(150);
}
}
}
}
if (input[3].equalsIgnoreCase("edit")) {
Thread.sleep(500);
System.
out.println("First type the number of the " + medium[1][0]
+
"\nyou want to edit");
int input4 = ScanObj.nextInt();
System.
out
.println(
"Now, type the number of the column you want to edit");
int input5 = ScanObj.nextInt();
System.
out.println("Now, make your edit:\n");
input[6] = ScanObj.nextLine();
medium[input4][input5] = input[6];
System.
out.println(medium[input4][input5]);
}
for (int y = 0; y < 10; y++) {
if (input[3].equalsIgnoreCase("search")) {
Thread.sleep(2000);
System.
out.println("Would you like to search by 1) Title or 2) Lexile #");
int input4 = 1;
input4 = ScanObj.nextInt();
Thread.sleep(2500);
System.
out.println("Now Type your search");
input[5] = ScanObj.nextLine();
Thread.sleep(2500);
for (int i = 0; i < 5; i++) {
System.
out.println(input4 + ", " + input[5]);
System.
out.println(medium[i][input4]);
if (input[5].compareToIgnoreCase(medium[i][input4]) == 0) {
y = 10;
System.
out.println("why do you lie");
for (int r = 0; r < 4; r++) {
if (r < 3)
System.
out.printf(medium[i][r] + " | ");
else
System.
out.println(medium[i][r]);
Thread.sleep(150);
}
}
else
System.
out.println(medium[i][input4]);
System.
out.println("Couldn't find item, please search again:");
}
}
}
}
}
}
Where ScanObj is my scanner. I'm just trying to get an Integer input, but it always returns null. What's wrong?
Here's an example using Scanner-
int choice;
do {
System.out.print("Would you like to search by (1) Title or (2) Lexile # : ");
choice = scan.nextInt();
} while(choice < 1 || choice > 2); // Keep asking the user for a valid integer
Above code will break, if the input is not an integer.
You can use nextLine-
Scanner scan = new Scanner(System.in);
String response;
do {
System.out.print("Would you like to search by (1) Title or (2) Lexile # : ");
response = scan.nextLine();
} while(!response.equals("1") && !response.equals("2"));
int choice = Integer.parseInt(response);
try {
System.out.print("Say cheeseeeee...");
Thread.sleep(3000);
} catch(InterruptedException e){
// handle exception
e.printStackTrace();
}
System.out.println("\nChoice : " + choice);

Categories

Resources