GeeCON Prague 2014*
The moose likes Beginning Java and the fly likes 2D array battleship Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "2D array battleship" Watch "2D array battleship" New topic
Author

2D array battleship

Haani Naz
Greenhorn

Joined: May 30, 2010
Posts: 23
Hi,

been reading up head first java. there's a bit about creating a battleship game and i just jumped ahead and tried doing it myself.

so far i managed to create a grid which populates ships denoted by 'x' in 3 cells. i'm having trouble getting the checks right if it tries to populate it in the same cells.


here is my code. please assist in giving me advice is getting it to work, i'd really appreciate it.







here's a working output for me:


row position: 2
board length marker 2: 6
board length marker 2: 5
board length marker 2: 4
row position: 0
board length marker 2: 6
board length marker 2: 5
board length marker 2: 4
row position: 4
board length marker 2: 6
board length marker 2: 5
board length marker 2: 4
Printing starts here..
x x x - -
- - - - -
x x x - -
- - - - -
x x x - -


non-working output:

row position: 2
board length marker 2: 6
board length marker 2: 5
board length marker 2: 4
row position: 1
board length marker 2: 6
board length marker 2: 5
board length marker 2: 4
row position: 1
col increment: 1
col increment: 2
col increment: 3
board length marker 2: 3



As you can see as soon as its the same row it fails to work. it also fails to print the grid : /

Thanks in advance.


Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3647
    
  16

The problem is that in your while loop, you check for three placed ships. i only gets increased if rowSpace >= 3, which will never happen if two ships are in the same row, because col gets incremented to 3, then once more to 4, and after that (5+1-col) will never be >= 3. So you're stuck in an infinite loop.

An important note about your code. NEVER use assignment expressions within another expression, like you do with rowSpace. Assign the value to rowSpace in the line before it, and then use rowSpace in the expression afterwards. When I saw the code I immediately thought your bug was there, because you had intended it to be an == instead of an =. So don't do it.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: 2D array battleship