• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

2D array battleship

 
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.


 
Saloon Keeper
Posts: 15529
364
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic