this code is my attempt at modifying a simple game i found in the book "head first java".. (pg-98 if anyone's interested)
the game is about sinking battleships! ...
actually... its just about declaring some blocks of a virtual array to comprise a battleship, and the user makes guesses about which blocks contain the battleship.
when all the correct blocks are guessed, the game ends, whith a display that the battleship has sunk.

my problem is that no matter how much i change the values and conditions, the for loops that control the number of times the user is asked to make a guess, always run a fixed number of time. which is equal to whatever size i declare the shipCell array in the line private int shipCell[]= new int[8]; of the 1st class... which,in this case, is 8.

this is my code for it(the nomenclature of the two classes follows from that in the book):

import java.util.Scanner;

class SimpleDotCom{
    private int hitNum=0,shipSize=0;
    private int shipCell[]= new int[8]; // this stores the blocks that comprise our battleship..
    Scanner input = new Scanner(System.in);

    // setters :

    public void setShipSize(int size){
        shipSize=size;  
    }
    public void setLocation(int cellLocation, int index){
        shipCell[index]=cellLocation;
    }
    public void setHitNum(int num){
        hitNum=num;
    }

    // getters :

    public int getShipSize(){
        return shipSize;
    }
    public int getHitNum(){
        return hitNum;
    }

    //methods :

    public void putShipInBattlezone(){

        for(int i=0;i<shipSize;i++){
            System.out.print("enter ship location (0 to 10) : ");
            setLocation(input.nextInt(),i);
        }   
    }


    public boolean checkHit(int guessedLocation,int size){

        boolean flag=false;
        for(int i=0;i<size;i++){

            if(shipCell[i]==guessedLocation){
                flag = true;
                break;          
            }
        }
        return flag;
    }

    public boolean checkSunk(int num){
        boolean sunkFlag=false;

        if(shipCell.length==num){ 
            sunkFlag=true;
        }

        return sunkFlag;
    }
    public void shipHasSunk(){
        System.out.print("ouch! you have sunk the ship!");  

    }

}

class SimpleDotComGame{

    public static void main (String [] args) {

        Scanner input = new Scanner(System.in);
        SimpleDotCom game = new SimpleDotCom();

        System.out.print("enter size of ship: "); // ship size entered
        game.setShipSize(input.nextInt());
        System.out.printf("entered ship size is: %d \n",game.getShipSize());

        game.putShipInBattlezone(); // ship is now put on battle feild, let the destruction begin

        int doFlag=0,hits=0;
        do{
            int guess=0; // make a guess
            System.out.print("enter guess (0 to 10) : ");
            guess=input.nextInt();

            if(game.checkHit(guess,game.getShipSize())){ // check if guess was correct

                System.out.println("hit");
                game.setHitNum(1+game.getHitNum()); // increments hitNum, which is initially 0
                hits=game.getHitNum();
                System.out.printf("total hits scored: %d \n",hits);

                if(game.checkSunk(hits)){ // passes incremented value of hitNum to sunk() to see if ship has sunk
                    doFlag=1;
                    game.shipHasSunk();
                    break;
                }
            }
            else{
                System.out.println("miss");
            }   
        }while(doFlag!=1); // until ship has sunk
    }
}

i'v just started learning java about a week or so, n im weak on concepts ... tried changing evrything i thought could be the problem, but it still remains.
would highly appreciate if someone could help me out in this code a bit :)

thanks
somjit :)

Recommended Answers

All 8 Replies

which loop do you mean?
also, if you're just in Java for a week: start with learning the concepts. first learn to walk, before you try to run.

Rather than just trying different things, add lots of print statements to your code to display the values of all the important variables and arrays wherever they are changed. Then you will be able to see exactly what is happening and where it's going wrong.

Rather than just trying different things, add lots of print statements to your code to display the values of all the important variables and arrays wherever they are changed.

i did that too... and thats what showed me that the do-while loop in the main() method was going 8 times(or whatever value i initialized the shipCell array with), even though i passed values like 3,4 etc, to the checkSunk() method, as it controls (to my understanding..) the running of the loop. but still nothing happened, and it keeps running 8 times... surely im not putting the statements in the right places ... but i cant figure out how to correct it... thats why i posted it here... any help would be really great :)

Seriously - you need more prints. Eg print the shipCell array after you have initialised it.
Some line of your code is not doing what you think it is - so trying to think your way out of this is unlikely to work. Use prints to check every stage in detail until you find the error. By definition the problem will be in one of the things you haven't checked yet, no matter how obviously right it may seem to you.
It may sound tedious but that's how real programmers find real bugs in real life - they may use a debugger to see the variables rather than using prints, but the process is the same.

(I did have a quick look at the logic, but nothing jumped out at me. I was confused by the naming vs the implementation - the naming suggests that there is one ship of length 8, but the logic seems more like 8 disconnected one-cell ships)

(I did have a quick look at the logic, but nothing jumped out at me. I was confused by the naming vs the implementation - the naming suggests that there is one ship of length 8, but the logic seems more like 8 disconnected one-cell ships)

the book called it virtual array, as if we have a array of a certain length, and, some of the blocks get "marked" i guess, and these marked elements are our "ships", so a number of blocks can be grouped together to form a "aircraft carrier", or individual blocks can be there too, like coast guard patrol boats... and the user has to "sink" them all... and "virtual" comes in here, because instead of actually creating that really long array in memory,and physically "marking" some of its blocks, just a few numbers are taken,representing the marked blocks, and stored in the shipCell array. thus we dont have to create that really big array anymore...

and...
as regards debugging using prints, doing them now :) lets see what i end up with... :)

Yes, I got the virtual array idea. Its just that for a single ship all the virtual indexes would be contiguous, but your program allows the user to select 8 at random. So "shipSize" is really "numberOfShips", etc.
Sorry to bang on about names, but mis-naming a variable is the very best possible way to obscure how the code may differ from the intent... OK, enough alteady. J.

i found out the bug...

the checkSunk() method was originally this:

public boolean checkSunk(int num){
        boolean sunkFlag=false;
        if(shipCell.length==num){ // this caused my problem
            sunkFlag=true;
        }

but it needs to be this:

    public boolean checkSunk(int num){
        boolean sunkFlag=false;         
        if(shipSize==num){ // corrected version
            sunkFlag=true;
        }           
        return sunkFlag;
    }

code runs ok now :) thanks for the debugging tip :) made me go over my code one line at a time:)

Excellent! Please mark this "solved" for our knowldge base.
See you next time... ;)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.