Tic Tac Toe, checking legal move - java

New to the site and have not been coding long. I am trying to find a way to check to see if the entered value is withing the array range as well as checking to see if the position is already occupied. I am running into trouble if the problems are not in order. I would like for it to catch the problem in any order and request them to enter another value, then recheck again. Thanks for any advice!
This is what I ended up doing. Any thoughts? Thanks again.
//in play game method
while(checkNotInBounds(move)){
System.out.println("Out of Bounds! Please try again...");
move = getMove(player);
}
while(!checkSpaceFree(move, boardValues)){
System.out.println("Space Taken! Please try again...");
move = getMove(player);
while(checkNotInBounds(move)){
System.out.println("Out of Bounds! Please try again...");
move = getMove(player);
}
//Method: checkInBounds
//Purpose: find out if move is in bounds
public static boolean checkNotInBounds(int[] move){
if(move[0] > 2 || move[0] < 0 || move[1] > 2 || move[1] < 0){
return true;}
return false;
}
//Method: checkFreeSpace
//Purpose: find if space is free
public static boolean checkSpaceFree(int[] move, char[][]boardValues){
if(boardValues[move[0]][move[1]] == ' '){
return true;}
return false;
}

Why not split it up into two methods instead of one as your trying to do two things there and switching isn't neccary then
do something like
public static boolean checkLegalMove(int[] move, char[][] boardValues){
if(move[0] > 2 || move[0] < 0 || move[1] > 2 || move[1] < 0){
return false;
}
if(boardValues[move[0]][move[1]] != ' '){
return false;
}
return true;
}
public void doSomething(boolean checkLegalMove(move,boardValues), char player){
boolean check = checkLegalMove(move,boardValues);
char temp = player;
if(check ==true ){
//do something to player
}else{
getMove(player);
}
}

Related

Method won't run because it returns no string

I'm creating a battleship game where a ship occupies 3 cells and you have to guess which cell. Once they guess it you return "hit" and if not you return "miss". Once they hit all 3 you return "kill". I've written the code but it states I still haven't returned a string.
public class SimpleBattleShip{
int[] shipCoordinates;
int numOfHits;
String updateStatus(int guess){
for(int i=0;i<shipCoordinates.length;i++){
if(guess == shipCoordinates[i]){
numOfHits++;
if(numOfHits ==3){
return "kill";
}else{
return "hit";
}
}else{
return "miss";
}
}
}
}
Have you tried just separating the NumberofHits If statement from the for loop. The problem may be the for loop iterating the whole 'hit check' for each value of 'i' which may cause it to put up false values before tallying the full amount of hits.
I've tried throwing in an else if to maybe tighten the parameters. turn it back to else if you want (this is for hit & miss).
public class SimpleBattleShip {
int[] shipCoordinates;
int numOfHits;
String updateStatus(int guess) {
for (int i = 0; i < shipCoordinates.length; i++) {
if (guess == shipCoordinates[i]) {
numOfHits++;
}
}
if (numOfHits == 3) {
return "kill";
} else if (numOfHits < 3 && numOfHits >= 1) {
return "hit";
} else {
return "miss";
}
}
}

Keeping track of path through a maze

The program is using backtracking to find out a way out of the maze(which it does fine). The problem occurs when I try to print out the correct path I took.
This is my solveMaze() method.
boolean result = false;
while(result==false){
if((row > 29) || (row < 0) || (col > 19) || (col < 0)) //check if position is within the array
return false;
if(maze[row][col].getVar().equals("E")) // check if youre at the exit
return true;
if(maze[row][col].getVar().equals("1")) // check if youre hitting a wall
return false;
if(maze[row][col].position.size() > 2){ // check if youre at an intersection
intersection[numIntersection] = maze[row][col]; // add intersection to intersection array
numIntersection++;
}
//this section does not need to be checked if youve never visited the position before
if(maze[row][col].getVisted() == true && numIntersection > 0){
if(intersection[numIntersection-1] == null)
return false;
else if(intersection[numIntersection-1] != null){ //as you backtrack to the last intersection pick up your "markers"
maze[row][col].setVar("0");
if(maze[row][col].position == intersection[numIntersection-1].position && intersection[numIntersection-1].getVisted()==true){ //remove intersection from the array as you pass back thru
maze[row][col].setVar("+");
intersection[numIntersection-1] = null;
numIntersection--;
}
}
}
if(maze[row][col].position.empty()==true) //check if the stack is empty
return false;
maze[row][col].position.pop();
if(maze[row][col].getVisted() == false)
maze[row][col].setVar("+"); //mark path as you land on unvisted positions
maze[row][col].setVisted(true);
//look north
if(solveMaze(row-1,col)== true)
return true;
//look east
if(solveMaze(row,col+1)== true){
return true;
}
//look west
if(solveMaze(row,col-1)== true){
return true;
}
//look south
if(solveMaze(row+1,col)== true){
return true;
}
}
return false;
}
As I backtrack I am picking back up my markers but it seems to be picking up markers on the correct path also and prints a maze with a broken up path.

Why is my break statement being ignored?

In my method under the if statement:
if (currentLocationX == 0 && currentLocationY == 4)
I have a break statement that should make the program exit out of the while loop and return true for 'answer' and for the method. Yet after some testing it seems that after returning true for 'answer', it goes back into the while loop giving the wrong results int the end. Why is my break statement not doing what it's supposed to? Thank you!
P.S. (this method calls on some other method that were not relevant to mention here)
public boolean solveMaze()
{
boolean answer = false;
int currentLocationX;
int currentLocationY;
//push starting location
pushX(2);
pushY(1);
while((isEmptyX() == false) && (isEmptyY() == false))
{
printMaze();
System.out.println();
currentLocationX = popX();
currentLocationY = popY();
//mark current location as visited
visited(currentLocationX, currentLocationY, maze);
System.out.println("Current Location: " + currentLocationX + ", " + currentLocationY);
if (currentLocationX == 0 && currentLocationY == 4)
{
answer = true;
break;
}
else
{
//push all unvisited OPEN neighbor locations into stack
if (checkEast(currentLocationX, currentLocationY) == 0)
{
pushX(eastX(currentLocationX));
pushY(eastY(currentLocationY));
}
else;
if (checkSouth(currentLocationX, currentLocationY)== 0)
{
pushX(southX(currentLocationX));
pushY(southY(currentLocationY));
}
else;
if (checkWest(currentLocationX, currentLocationY)== 0)
{
pushX(westX(currentLocationX));
pushY(westY(currentLocationY));
}
else;
if (checkNorth(currentLocationX, currentLocationY)== 0)
{
pushX (northX(currentLocationX));
pushY(northY(currentLocationY));
}
else;
}
}
return answer;
}
I wrote out the basic logic of your method as
public static boolean solveMaze() {
boolean answer = false;
int currentLocationX = 0;
int currentLocationY = 4;
while (true) {
if (currentLocationX == 0 && currentLocationY == 4) {
System.out.println("Hit the break");
break;
} else {
System.out.println("Missed the break");
}
}
return answer;
}
and if you execute it you get Hit the break. So your solveMaze() method is fine in terms of breaking out of the loop once it satisfies your if-statement. I would say that if you see your code subsequently going back into the while loop, it must be that solveMaze() was called a second time.

How to compare three boolean values

Compare three boolean values and display the first one that is true.
Hey guys, I am trying to write a program that compares three boolean values and displays the first true one. I am comparing three words for their length, and it will display the longest. The error that I am getting is that my else tags aren't working. Take a look at the code.
//Check which word is bigger
if (len1 > len2)
word1bt2 = true;
if (len2 > len3)
word2bt3 = true;
if (len1 > len3)
word1bt3 = true;
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true);
System.out.println(wor1);
else if (word2bt3 == true);
System.out.println(wor2);
else System.out.println(wor3);
I have set boolean values for word1bt2, word2bt3 and word1bt3. In eclipse, I am getting a syntax error under the elses in my code above. Any help would be great!
if (word1bt2 == true && word1bt3 == true);
Is wrong, you need to remove the semicolon:
if (word1bt2 == true && word1bt3 == true)
Same for the elses
else (word2bt3 == true);
Is wrong too, it should be
else if (word2bt3 == true)
Side note: boolean values can be used as condition, so your if statements should be
if (word1bt2 && word1bt3) // The same as if (word1bt2 == true && word1bt3 == true)
How to compare three boolean values?
Dont!
If you find yourself needing to compare three variable you may as well cater for any number of variables immediately - there's no point hanging around - do it properly straight away.
public String longest(Iterator<String> i) {
// Walk the iterator.
String longest = i.hasNext() ? i.next() : null;
while (i.hasNext()) {
String next = i.next();
if (next.length() > longest.length()) {
longest = next;
}
}
return longest;
}
public String longest(Iterable<String> i) {
// Walk the iterator.
return longest(i.iterator());
}
public String longest(String... ss) {
// An array is iterable.
return longest(ss);
}
Remove the ; and change it with brackets {}.
if (word1bt2 && word1bt3) {
System.out.println(wor1);
} else if (word2bt3) {
System.out.println(wor2);
} else {
System.out.println(wor3);
}
Issue with the else blocks: use {} insteaad of () to enclose instructions...
Remove the ; at the first if!!!!! - Quite common mistake, with very puzzling results!
//Check which word is the longest
if (word1bt2 == true && word1bt3 == true) { //leave ; and always add bracket!
System.out.println(wor1);
}
else if(word2bt3 == true)
{
System.out.println(wor2);
}
else {
System.out.println(wor3);
}
if you need a condition in an else branch, you have to use if again - plain else won't have such a feature...
ALWAYS use brackets for bodies of if statements, loops, etc!!!
Be extremely careful NOT to use ; in the lines that don't behave well with it:
if statements
for loops
while() {...} loops' while statement
try this, if lenght are equal then s1 is considered as Bigger. Also i have not added null check
public class Test {
public static void main(String[] args) {
String word1 = "hi";
String word2 = "Hello";
String word3 = "Hell";
String Bigger = null;
if(word1.length() >= word2.length() && word1.length() >= word3.length() ){
Bigger = word1;
}else if(word2.length() >= word1.length() && word2.length() >= word3.length()){
Bigger = word2;
}else if(word3.length() >= word2.length() && word3.length() >= word1.length()){
Bigger = word3;
}
System.out.println(Bigger);
}
}

While loop: Need assistance

I can't find the problem that causes my while loop not to work.
When I run the program and press a radio button, I get this error code:
Syntax error, insert "while ( Expression ) ;" to complete DoStatement
Here is my loop:
int i = 1;
boolean x;
//for (i = 0; i < 6; i++) {
do{
warning.setText(" FEL!");
i++;
while(x == false);{
if(e.getSource() == buttonOK){
if(buttonDollar.isSelected() == false){
x = false;
}
if(buttonEuro.isSelected() == false){
x = false;
}
if(buttonPund.isSelected() == false){
x = false;
}
if(buttonKrona.isSelected() == false){
x = false;
}
break;
}
}
}
You are missing the syntax for "while" element
From the sun site (I am guessing that this is java)
do {
statement(s)
} while (expression);
I think you need a closing curly brace before the while
do{
warning.setText(" FEL!");
i++;
}while(x == false);
The whole structure is all wrong, you're looking to do something very simple:
if(e.getSource() == buttonOK)
{
if( !buttonDollar.isSelected() && !buttonEuro.isSelected()
&& !buttonPund.isSelected() && !buttonKrona.isSelected() )
{
warning.setText(" FEL!");
}
}
From a UI perspective, it's better to ensure that one radio button is always selected (as this is what your users will likely expect).

Categories