i dont understand the reason why im geting the errors i am with this code... errors with arraylists, also a few other errors like symbol not found etc s.. i corrected the ones i could, but the ones (5 of them in total )im still geting, i dont understand them...

the code is my version of a battleship game found in head first java, 6th chapter..
it takes user input on number of ships, and allocates some blocks to them, when all blocks are hit, the ship sinks, and when all ships are sunk... you win the game...

this is the code:

import java.util.Scanner;
import java.util.ArrayList;

class ship{
    private int shipSize=0;
    private String shipName;
    ArrayList<int> shipCell = new ArrayList<int>();


    // setters :
    public void setShipName(String name){
        shipName=name;  
    }
    public void setShipSize(int size){
        shipSize=size;  
    }
    public void setLocation(int cellLocation){
        shipCell.add(cellLocation);
    }

    // getters :

    public int getShipSize(){
        return shipSize;
    }

    //methods :

    public void putShipInBattlezone(int start){

        // int seed = (int)((Math.random()*15)+5); // for later use, once the simpler version runs errorfree
        // int randomNum=(int)(Math.random()*10); // the virtual array is of size 15

        for(int i=0;i<shipSize;i++){         
            setLocation(start+i);
        }
        System.out.println("\n\nbattleship placed.. let the destruction begin!!\n\n......................................................");
    }

    public boolean checkHit(int guessedLocation/*,int size*/){

        //System.out.printf("in checkHit, location passed: %d  size passed: %d \n",guessedLocation,size);
        System.out.printf("in checkHit, location passed: %d \n",guessedLocation);
        boolean checkHitFlag=shipCell.contains(guessedLocation);

        if(checkHitFlag){
            shipCell.remove(guessedLocation); // arrayList shrunked         
        }
        return checkHitFlag;
    }

    public boolean checkSunk(){

        System.out.printf("\nin checksunk,\n");
        boolean sunkFlag=shipCell.isEmpty();
        return sunkFlag;
    }
    public void shipHasSunk(){
        System.out.print("Bravo!! you have sunk the %s!",shipName); 
    }   
}

class BattleShipEnhanced{
    Scanner input = new Scanner(System.in);
    ArrayList<ship> shipList = new ArrayList<ship>();
        private void setUpGame(){

            System.out.print("enter number of ships: ");
            int numOfShips=input.nextInt();
            ship[] game = new ship[numOfShips]; // game>> refernce to array object of type SimpleDotCom (our ship class)


            for(int i=0;i<numOfShips;i++){

                //get a name for a instance to create
                System.out.print("enter name of ship: ");
                // create an instance of this nae of ship class
                game[i]= new ship();
                game[i].setShipName(input.nextLine());

                //set size
                System.out.print("enter size of ship: "); // ship size entered
                game[i].setShipSize(input.nextInt());       

                //place it on battlezone
                System.out.print("enter starting cell of ship: ");
                game[i].putShipInBattlezone(input.nextInt());       

                //put the newly created instance inside array list
                shipList.add(game[i]);
            }
        }

        private void startPlaying(){
            while(!shipList.isEmpty()){
            int guess=0; // make a guess
            System.out.print("enter guess (+ve values only) : ");
            guess=input.nextInt();
            checkGuess(guess);
            }
            finishGame();// finishes game when arrayList is empty
        }

        private void checkGuess(int guess){

            for(ship currentShip : shipList){
                if(currentShip.checkHit(guess)){ // check if guess was correct

                    System.out.println("hit\n");


                    if(currentShip.checkSunk()){ 
                        CurrentShip.shipHasSunk();
                        shipList.remove(CurrentShip);// shipList shrunk
                    }
                }
                else{
                    System.out.println("miss");
                }
            }
        }
        private void finishGame(){

            System.out.println("you have sunk all the ships!! go get soe drinks!");     

        }

    public static void main (String [] args) {

    BattleShipEnhanced game = new BattleShipEnhanced();
    game.setUpGame();
    game.startPlaying();
    }
}

any help would be really great... iv worked hard on this, n a bit disheartened with the errors that still remain.. really hoping to get this to compile and run error free :)

thanks
somjit :)

Whenever you got an error saying Symbol not found, you need to check the name given by the error. There are usually 2 causes of this type of exception.

One, Java language is case-sensitive. In other words, a variable name Number is not the same as a variable name number. If you accidentally mistype either name or letter case, you could easily get the exception.

Another, you attempt to call a method which does not exist in the class. Again, this is also a case-sensitive.

Your case seems to be the former. For example, lines 113 & 114, you declare currentShip variable but use CurrentShip instead. The rest, look for the line number in your error & the name.

By the way in line 7, you cannot declare an ArrayList using primitive type. Try class Integer instead.

commented: nice suggestion +3

as Taywin says:
You have to create ArrayList with Integer class,not twith primitive data type like int.
Just try with it.

my errors are fixed!! thank you so much :) but now as i run them, another error is coming in...
in this loop:

for(int i=0;i<numOfShips;i++){

                // create an instance of the ship class
                game[i]= new ship();

                //get a name for a instance to create
                System.out.print("enter name of ship: ");
                game[i].setShipName(input.nextLine());

                //set size
                System.out.print("enter size of ship: "); // ship size entered
                game[i].setShipSize(input.nextInt());       

                //place it on battlezone
                System.out.print("enter starting cell of ship: ");
                game[i].putShipInBattlezone(input.nextInt());       

                //put the newly created instance inside array list
                shipList.add(game[i]);
            }

the entire game[i].setShipName(input.nextLine()); part gets skipped, and the program goes to the part where it asks to enter size of the ship.

in C, this happened when mixing formatted and unformatted input, like getchar() after a scanf(), is something like that happening here too?? im guessing the input.nextLine() method is reading a newline character from the input stream, and hence returns without taking user input.. is that whats happening here ?? any way i can fix this... ?

thanks again :)
somjit.

Yes, mixing nextInt and nextLine is a problem. Unline nextLine, which consumes the new line charater at the end ofthe line, nextInt takes the int and leaves the following new line character in the buffer, so the next readLine reads up to that newline (ie a zero length String).
There are a number of ways to avoid this - maybe the simplest is a quick "throw away" nextLine after the nextInt to consume the newline and leave the Scanner at the start of the next line as expected.

maybe the simplest is a quick "throw away" nextLine after the nextInt to consume the newline and leave the Scanner at the start of the next line as expected.

this works :) but is there a better way to do this? something like check input stream untill a white space is encountered, and clear that whitespace from the stream? thus keeping the stream pristine?

Personally I prefer not to use Scanner at all. Just read whole lines from a BufferedReader and parse fields, ints, dates etc etc using the methods in the appropriate classes. Maybe I'm just a control freak.
But seriously, the extra readLine is a perfectly good solution, and very commonly used.

Personally I prefer not to use Scanner at all.

in a lot of videos, im seeing poeple opt for BufferdReader over Scanner, they say its more effective, ur amongst them too it seems :) ... i dont really know much about BufferedReader, nor Scanner for that matter. a few days ago, was searching on how to add user inputs, found a video using Scanner, i liked it, and so just stuck to it since then. can u give a short explanation on the advantages in using BufferedReader? a few links too perhaps?

thanks :)

Scanner is a pre-packaged reading/parsing class that gives novices a one-stop solution to processing simple text stream input. Apart from the nextInt/nextLine issue that you (and pretty much everybody else) ran into, it does a decent job within its design scope.
You use BufferedReader if you want to take control over all the parsing yourself, eg to parse input that's too complex for Scanner, eg dates or oddly-delimited multiple fields. Sooner or later you will get to that place, after which you will have climbed the learning curve, and will have no further need of Scanner. In the meantime there's no harm in doing it the easy way and using Scanners.

Sooner or later you will get to that place, after which you will have climbed the learning curve, and will have no further need of Scanner. In the meantime there's no harm in doing it the easy way and using Scanners.

that sounds good :)

but , as regards my code, its running into a java.util.ConcurrentModificationException problem... its like, im stating how many ships there will be, and the game setup goes fine, the program asks the user to make guesses, and sinks the ship like it should, its all seems fine, but when all the ships are sunk, and the game should end,im getting this exception... any help? (again.. :| )

i did read about this exception in the java api docs, and understand what causes it, but im a bit lost on how to modify my code so that it doesnt occur.

this is the initial (n a few later) error corrected version which is giving the above exception:

import java.util.Scanner;
import java.util.ArrayList;

class ship{
    private int shipSize=0;
    private String shipName;
    ArrayList<Integer> shipCell = new ArrayList<Integer>();


    // setters :
    public void setShipName(String name){
        shipName=name;  
    }
    public void setShipSize(int size){
        shipSize=size;  
    }
    public void setLocation(int cellLocation){
        shipCell.add(cellLocation);
    }

    // getters :

    public int getShipSize(){
        return shipSize;
    }

    //methods :

    public void putShipInBattlezone(int start){

        // int seed = (int)((Math.random()*15)+5);
        // int randomNum=(int)(Math.random()*10); // the virtual array is of size 15

        for(int i=0;i<shipSize;i++){         
            setLocation(start+i);
        }
        System.out.println("\n\nbattleship placed.. \n\n");
    }

    public boolean checkHit(int guessedLocation/*,int size*/){

        //System.out.printf("in checkHit, location passed: %d  size passed: %d \n",guessedLocation,size);
        System.out.printf("in checkHit, location passed: %d \n",guessedLocation);
        boolean checkHitFlag=shipCell.contains(guessedLocation);

        if(checkHitFlag){
            int index = shipCell.indexOf(guessedLocation);
            shipCell.remove(index); // arrayList shrunked       
        }
        return checkHitFlag;
    }

    public boolean checkSunk(){

        System.out.printf("\nin checksunk,\n");
        boolean sunkFlag=shipCell.isEmpty();
        return sunkFlag;
    }
    public void shipHasSunk(){
        System.out.printf("Bravo!! you have sunk the %s!",shipName);    
    }   
}

class BattleShipEnhanced{
    Scanner input = new Scanner(System.in);
    ArrayList<ship> shipList = new ArrayList<ship>();
        private void setUpGame(){

            System.out.print("enter number of ships: ");
            int numOfShips=input.nextInt();
            ship[] game = new ship[numOfShips]; // game>> refernce to array object of type SimpleDotCom (our ship class)


            for(int i=0;i<numOfShips;i++){

                // create an instance of this nae of ship class
                game[i]= new ship();
                //get a name for a instance to create
                System.out.print("enter name of ship: ");
                input.nextLine();
                game[i].setShipName(input.nextLine());

                //set size
                System.out.print("enter size of ship: "); // ship size entered
                game[i].setShipSize(input.nextInt());       

                //place it on battlezone
                System.out.print("enter starting cell of ship: ");
                game[i].putShipInBattlezone(input.nextInt());       

                //put the newly created instance inside array list
                shipList.add(game[i]);
            }
        }

        private void startPlaying(){
            while(!shipList.isEmpty()){
            int guess=0; // make a guess
            System.out.print("enter guess (+ve values only) : ");
            guess=input.nextInt();
            checkGuess(guess);
            }
            finishGame();// finishes game when arrayList is empty
        }

        private void checkGuess(int guess){

            for(ship currentShip : shipList){
                if(currentShip.checkHit(guess)){ // check if guess was correct

                    System.out.println("hit\n");


                    if(currentShip.checkSunk()){ 
                        currentShip.shipHasSunk();
                        shipList.remove(currentShip);// shipList shrunk
                    }
                }
                else{
                    System.out.println("miss");
                }
            }
        }
        private void finishGame(){

            System.out.println("you have sunk all the ships!! go get some drinks!");        

        }

    public static void main (String [] args) {

    BattleShipEnhanced game = new BattleShipEnhanced();
    game.setUpGame();
    game.startPlaying();
    }
}

You didn't say where the exception was being thrown, but maybe its like this:

for(ship currentShip : shipList){
   ...
   shipList.remove(currentShip)

You can't add or delete members from a list when you're in the middle of iterating thru it with an ordinary Interator or an enhanced for loop.

The easiest fix (provided the list isn't gargantuan big) is to create a temp copy of the original list to iterate thru, then you can delete from the original with no problems

ArrayList<ship> temp = new ArrayList<ship>(shipList);
for(ship currentShip : temp){
   ...
   shipList.remove(currentShip)

Or, if you want to be a real ninja java master, use a ListIterator

ps: "Ship" not "ship" for a class name

this is what the java gives me ...

Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:819) 
at java.util.ArrayList$Itr.next(ArrayList.java:791)                   
at BattleShipEnhanced.checkGuess(BattleShipEnhanced.java:108)         
at BattleShipEnhanced.startPlaying(BattleShipEnhanced.java:101)       
at BattleShipEnhanced.main(BattleShipEnhanced.java:134)

and regarding the temp, and Listiterator, im gonna look at your suggestions right now :) also, thanks for the nomenclature tip :) it gets confusing with all the uppercase and lowercase and where to use them n how n all......! :P

ps: i think i need to find a better word than "nomenclature".... just.tooBig()! feels misplaced everytime i write it anywhere related to programming :|

The easiest fix (provided the list isn't gargantuan big) is to create a temp copy of the original list to iterate thru, then you can delete from the original with no problems

yaayyy!! it works!! im sinking ships like never before!! :D

will be looking at the listiterator and the naming conventions now..
(after i sinkSomeMoreShips() that is.. :D )

this problem : solved.

thank you so much :)
somjit.

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.