Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

2D array battleship

 
Haani Naz
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 5912
65
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic