Results 1 to 9 of 9
  1. #1
    JavaJimme is offline Member
    Join Date
    Nov 2012
    Posts
    30
    Rep Power
    0

    Default HeadFirst Java code

    Somebody read the book Head First Java? I can't seem to let the code beginning to work.
    It's page 145-155 were I'm stuck, all the lines seems to work except one part, here is are the codes.
    I'm sorry for this noob question but I'm stuck on this for days!

    Main:
    Java Code:
    import java.util.*;
    
    
    
    public class DotComBust {
    
    
        
        
    
    
            
            private GameHelper helper = new GameHelper();
            private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
            private int numOfGuesses = 0;
            
            
            private void setUpGame(){
                DotCom one = new DotCom();
                one.setName("Pets.com");
                DotCom two = new DotCom();
                two.setName("eToys.com");
                DotCom three = new DotCom();
                three.setName("Go2.com");
                dotComsList.add(one);
                dotComsList.add(two);
                dotComsList.add(three);
                
                System.out.println("Your goal is to sink three dot coms.");
                System.out.println("Pets.com, eToys.com, Go2.com");
                System.out.println("Try to sink them all in the fewest number of guesses");
                
                for (DotCom dotComToSet : dotComsList){  //repeat with each DotCom in the list.
    
                    ArrayList<String> newLocation = helper.placeDotCom(3);   //Ask the helper for a DotCom location (an ArrayList of Strings).
                    
                    dotComToSet.setLocationCells(newLocation);  //call the setter method on this DotCom to give it the location you got from the helper.
                    
                }//close for loop
                
                }//close setUpgame method
                
            
            private void startPlaying(){
                
                while (!dotComsList.isEmpty()){
                    
                    String userGuess = helper.getUserInput("Enter a guess");
                    checkUserGuess(userGuess);
                } //close while
                finishGame();
            } //close startPlay methode
            
            
            private void checkUserGuess(String userGuess){
                numOfGuesses++;
                String result = "miss";
                for(DotCom dotComToTest : dotComsList){
                    result = dotComToTest.checkYourself(userGuess);
                    if (result.equals("hit")){
                        break;
                    }
                    if (result.equals("kill")){
                        dotComsList.remove(dotComToTest);
                        break;
                        }
                }// close for
            } //close methode
            
            
        
            private void finishGame(){
                System.out.println("All Dot Coms are Dead! Your stock is now worthless.");
                if(numOfGuesses <= 18){
                    System.out.println("It only took you " + numOfGuesses + "guesses.");
                    System.out.println(" You got out before your options sank.");
                }else {
                    System.out.println("Took you long enough. "+ numOfGuesses + " guesses.");
                
                System.out.println("Fish are dancing with your options");
            
            }    //end else
    } //end methode
        
        
        
        
        
        
        public static void main(String[] args) {
            DotComBust game = new DotComBust();
            game.setUpGame();
            game.startPlaying();
        } //close methode
        
        
    }// end class

    Methodes:

    Java Code:
    import java.util.ArrayList;
    
    public class DotCom {
        
    private ArrayList<String>locationCells;
    private String name;
        
        public void setLocationCells(ArrayList<String> loc){
            locationCells = loc;
    }
        public void setName(String n){
            name = n;
    }
    
    
        
        public String checkYourself(String userInput){
            String result = "Miss";
            
            int index = locationCells.indexOf(userInput);
            if (index >=0){
                locationCells.remove(index);
            
            if (locationCells.isEmpty()){
                result = "kill";
                System.out.println("Ouch! You sunk "+name + "      : (");
                }else{
                    result = "hit";
                } //close if
            }//close if
            return result;
        } //close methode
    } //close class
    Gamehelper:
    Java Code:
    import java.io.*;import java.util.*;
    
    
    
    
    public class GameHelper {
    
    
        private static final String alphabet = "abcdefg";
        private int gridLength = 7;
        private int gridSize = 49;
        private int [] grid = new int [gridSize];
        private int comCount = 0;
        
        public String getUserInput (String prompt){
            String inputLine = null;
            System.out.println(prompt + " ");
            try{
                BufferedReader is = new BufferedReader(
                    new InputStreamReader(System.in));
                    inputLine = is.readLine();
                    if (inputLine.length() == 0) return null;
            }catch (IOException e){
                System.out.println("IOException: " + e);
            }
            return inputLine.toLowerCase();
        }
        
    //     method, placeDotCom, takes an int as a parameter, and returns an ArrayList of Strings  
         public ArrayList<String> placeDotCom(int comSize) {                  
            // declare ArrayList alphaCells  
            ArrayList<String> alphaCells = new ArrayList<String>();  
            // declare an array to hold the coordinates, size is equal to comSize  
            String [] alphacoords = new String [comSize];        
            // declare a string to be used for concatenation  
            String temp = null;                                 
            // declare an array to hold candidate coordinates  
            int [] coords = new int[comSize];                    
            // counter to keep track of how many attempts  
            int attempts = 0;                                    
            // if success is true, that means it's a good place to hide the "dot com"   
            boolean success = false;                             
            int location = 0;                                  // current starting location  
              
            // comcount is one of the member variables. It keeps track of how many dot coms are placed  
            comCount++;                                        // nth dot com to place  
              
            // this section says to place the dot com vertically if it's on an odd number  
            int incr = 1;                                      // set horizontal increment  
            if ((comCount % 2) == 1) {                         // if odd dot com  (place vertically)  
              incr = gridLength;                               // set vertical increment  
            }  
          
            // this while loop figures out where in the array to place the dot com...  
            // ... it keeps going until success == true, or until it searches 200 times  
            while ( !success & attempts++ < 200 ) {             // main search loop  (32)  
            location = (int) (Math.random() * gridSize);      // get random starting point  
                //System.out.print(" try " + location);  
            int x = 0;                                        // nth position in dotcom to place  
                success = true;                                 // assume success  
                while (success && x < comSize) {                // look for adjacent unused spots  
                  if (grid[location] == 0) {                    // if not already used  
                     coords[x++] = location;                    // save location  
                     location += incr;                          // try 'next' adjacent  
                     if (location >= gridSize){                 // out of bounds - 'bottom'  
                       success = false;                         // failure  
                     }  
                     if (x>0 & (location % gridLength == 0)) {  // out of bounds - right edge  
                       success = false;                         // failure  
                     }  
                  } else {                                      // found already used location  
                      // System.out.print(" used " + location);    
                      success = false;                          // failure  
                  }  
                }  
            }                                                   // end while  
          
            // this section takes the successful find and turns it into coordinates for the game  
            int x = 0;                                          // turn good location into alpha coords  
            int row = 0;  
            int column = 0;  
            // System.out.println("\n");  
            while (x < comSize) {  
              grid[coords[x]] = 1;                              // mark master grid pts. as 'used'  
              row = (int) (coords[x] / gridLength);             // get row value  
              column = coords[x] % gridLength;                  // get numeric column value  
              temp = String.valueOf(alphabet.charAt(column));   // convert to alpha  
                
              // add the coordinate to the arraylist  
              alphaCells.add(temp.concat(Integer.toString(row)));  
              x++;  
          
              // System.out.print("  coord "+x+" = " + alphaCells.get(x-1));  
                
            }  
            // System.out.println("\n");  
              
            return alphaCells; // send the arraylist back to be used by the game  
           }      
    }

    Eclipse seems to compile everything except one part of the main code:

    Java Code:
    for (DotCom dotComToSet : dotComsList){                
    
    
                    ArrayList<String> newLocation = helper.placeDotCom.(3);
                    
                    dotComToSet.setLocationCells(newLocation);
                    
                }//close for loop
                
                }//close setUpgame method
    The .placeDotCom(3); is underscored with red, and can't compile I did everything exactly the same as in the book, running it on version 5.0 but it just doesn't seem to work. Can somebody please help me I'm stuck on this for days!
    Last edited by JavaJimme; 11-22-2012 at 12:30 AM.

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: HeadFirst Java code

    Java Code:
    ArrayList<String> newLocation = helper.placeDotCom.(3);
    That line doesn't make a lot of sense. What is it supposed to do?

  3. #3
    JavaJimme is offline Member
    Join Date
    Nov 2012
    Posts
    30
    Rep Power
    0

    Default Re: HeadFirst Java code

    Quote Originally Posted by pbrockway2 View Post
    Java Code:
    ArrayList<String> newLocation = helper.placeDotCom.(3);
    That line doesn't make a lot of sense. What is it supposed to do?
    Thats the only part were I get an error with Eclipse, if that part of code is fixed it should work.
    I edited that part of code in the post with some // commments to be more clear.
    It's suppose to ask the helper for a DotCom location(an ArrayList of Strings)
    Last edited by JavaJimme; 11-22-2012 at 12:29 AM.

  4. #4
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,565
    Rep Power
    12

    Default Re: HeadFirst Java code

    Then the general syntax to use is <instance>.<method>(<arguments>). Ie the second "dot" in the expession you used shouldn't be there.

  5. #5
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,193
    Rep Power
    19

    Default Re: HeadFirst Java code

    Since the problem isn't IDE-specific, I've moved the thread here from the Eclipse section.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  6. #6
    JavaJimme is offline Member
    Join Date
    Nov 2012
    Posts
    30
    Rep Power
    0

    Default Re: HeadFirst Java code

    Quote Originally Posted by pbrockway2 View Post
    Then the general syntax to use is <instance>.<method>(<arguments>). Ie the second "dot" in the expession you used shouldn't be there.
    Thank you for your reply and sorry for wrong section, I was abit in a hurry when I posted.
    Anyway that "dot" I must have typed it by mistake when I was copy pasting this code cos it wasnt there in the original code.

    So placeDotCom(3) is still underscored with red, but eclipse says: The method placeDotCom(int) is undefined for the type GameHelper. Why? :((((

  7. #7
    wsaryada is offline Senior Member
    Join Date
    Jun 2007
    Location
    Bali, Indonesia
    Posts
    758
    Rep Power
    8

    Default Re: HeadFirst Java code

    I have try to compile your code and it compile successfully. Maybe you can clean up you eclipse work space and try compile it again.
    Last edited by wsaryada; 11-23-2012 at 02:43 AM.

  8. #8
    JavaJimme is offline Member
    Join Date
    Nov 2012
    Posts
    30
    Rep Power
    0

    Default Re: HeadFirst Java code

    Quote Originally Posted by wsaryada View Post
    I have try to compile your code and it compile successfully. Maybe you can clean up you eclipse work space and try compile it again.
    Thanks for trying that out, seems its my eclipse after all, I did project>clean if you meant that. And it's still underscored with red... Makes me crazy :(

  9. #9
    JavaJimme is offline Member
    Join Date
    Nov 2012
    Posts
    30
    Rep Power
    0

    Default Re: HeadFirst Java code

    Ah I just solved the mystery :) I had 2 GameHelper classes in 2 different projects and the one that had the correct code was in another project.. Jesus how noob of me :( Thanks for the tip for checking out the eclipse workspace, I thought it was the code that made the error until I read your post ;)

Similar Threads

  1. Replies: 16
    Last Post: 01-31-2012, 08:36 PM
  2. Translate Vb.net code into Java code
    By Radu in forum New To Java
    Replies: 5
    Last Post: 04-12-2011, 09:27 AM
  3. Replies: 0
    Last Post: 02-21-2011, 11:50 AM
  4. Convert java code to midlet code
    By coldvoice05 in forum New To Java
    Replies: 1
    Last Post: 08-12-2009, 11:14 AM
  5. Convert java code to midlet code
    By coldvoice05 in forum Advanced Java
    Replies: 1
    Last Post: 08-09-2009, 01:21 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •