• 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
  • Tim Cooke
  • Liutauras Vilda
  • Jeanne Boyarsky
  • paul wheaton
Sheriffs:
  • Ron McLeod
  • Devaka Cooray
  • Henry Wong
Saloon Keepers:
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Tim Moores
  • Mikalai Zaikin
Bartenders:
  • Frits Walraven

Head First Java Programs

 
Ranch Hand
Posts: 93
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Dear Programmers,
I have been reading 'Head First Java' anyway, after a certain point, to run the programs therin it was necessary to install jdk 6.0, which I did, but I still get compiler error returns, even upon using code lifted directly from the headfirstlabs.com site. The book recommends this site (JavaRanch) to discuss whatever problems are thus encountered. I encountered such problems on pages 150 - 3, with the programs DotCom, DotComBust and GameHelper. They all return compiler errors, so I can't play the version of 'Battleships' as outlined.
It seems even though I am using the jdk 6.0 - the compiler won't recognise the 'enhanced loops' nor other stuff - like 'input streams' - just like the jdk 1.2 didn't. I could go into greater detail as to the error returns, but would like to know if there is a sub-site in Java Ranch that might deal with this conumdrum.
Thank you for your assistance.
Yours
Simon Evans
 
Ranch Hand
Posts: 191
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please state the compiler errors exactly and we might be able to help. I'm unsure if we can solve all your problems given that we are not all familair with 'Head First Java' but we might be able to point you in the right direction.

Sam
[ March 27, 2008: Message edited by: Sam Bluesman ]
 
Marshal
Posts: 79922
395
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I couldn't see anything about your particualr problem in the Javaranch FAQ. It is nice to see HFJ recommending us, but that was probably printed before I signed on.
You should have no difficulty getting enhanced for loops to run on jdk1.6.0. Try writing this at a terminal: java -version

Also
javac -version

Both ought to give something with 1.6 in.

If you are getting compiler errors about not being able to access enhanced for loops you appear to have got a JDK somewhere, but it must be an old one, 1.4.2 or older. And as Sam Bluesman has already told you, it is easier to help if we know the exact details of what you are doing.
 
Campbell Ritchie
Marshal
Posts: 79922
395
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Please don't send PMs about replies to posts. You ought to have posted what you sent me here, and used code tags (below the mesage window) around the code. Please post your code here, so everybody can learn from it.

Make sure not to copy code onto the Ranch by hand, but use copy-and-paste. That way you quote the exact code rather than potentially adding spelling errors. In fact about 80% of the compiler errors you got are misspellings.

Are you using an IDE? Probably not a good idea for beginners. Best to get used to using a text editor; since you appear to be on Windows I suggest you try Notepad++ (try here) which supports syntax highlighting automatic indentation and bracket pairing highlighting.

In fact, I think that if you check your code for misspelllings, unpaired brackets and wordWhichShouldBeOneWord div ided in pa rts, you will reduce your list of errors to about 2. If you check for places where there ought to be a = operator which you have missed out, you can probably get rid of the other two.
 
Campbell Ritchie
Marshal
Posts: 79922
395
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Actually, I think I may have been a bit harsh. Sorry.

Your list of errors read

C:\Java Head First>javac DotCom.java
DotCom.java:8: <identifier> expected
private ArrayList< String> locationCells;
^
DotCom.java:13: <identifier> expected
public void setLocationCells(ArrayList<String>loc)
^
DotCom.java:66: ')' expected
^
3 errors

C:\Java Head First>javac DotComBust.java
DotComBust.java:9: <identifier> expected
private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
^
DotComBust.java:42: ';' expected
for (DotCom dotComToSet : dotComsList)
^
DotComBust.java:52: illegal start of expression
}
^
DotComBust.java:51: ';' expected
^
DotComBust.java:80: ';' expected
for (DotCom dotComeToTest: dotComsList)
^
DotComBust.java:108: illegal start of expression
}
^
DotComBust.java:107: ';' expected
^
7 errors

C:\Java Head First>javac GameHelper.java
GameHelper.java:34: ';' expected
inputLine is.readLine();
^
GameHelper.java:51: <identifier> expected
public ArrayList<String>placeDotCom(int comSize)
^
GameHelper.java:149: ';' expected
^
3 errors

Trying to compile what you sent me in the PM gave a different set of errors; I can only go by what you sent me.What I have found are:
  • DotCom - instead of = after index, double )) after "ouch! you sank . . ."
  • GameHelper: = missing after inputLine, comSize misspelt twice, ) missing and ) doubled after ==0
  • DotComBust: helper dotComsList and dotComToTest misspelt, ) missing or )) doubled after ==0
  • You will have to go through your own code and check for those errors.
     
    Simon Evans
    Ranch Hand
    Posts: 93
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Dear Programmers,

    I have previously posted this matter, and seem to have ended up taking culpability for code, which although published to hard copy (Head First Java p150-2) and to the net (www.headfirstlabs.com Chapter 6) doesn't compile.

    I was told not to send the code as a personal message to 'RanchHands' but to the Post Reply option, so this is what I am now doing.

    I am quoting the code as I read it, and anyone if they have the book, or wishes to look at the site code can check thus, that it is not my fault if there are errors, besides if there were no errors, programs would compile, and I would not be asking about it.

    I have installed the jdk 6.0 to my computer, and 'javac' wouldn't be legible as a command if it were not in the jdk's established classpath, which it is, but all the same compiler seems to point to the enhanced loops, and to establishment of input stream object, and arraylist classes though I was given to understand these are jdk6.0 legible.

    Without wishing to put the cart before the horse, so's to speak, this is the response to my compiler re: DotCom, DotComBust and GameHelper (on pages 150, 148=9 & 152 HFJ, respectively) :-

    ***************************************************************************
    Microsoft Windows XP [Version 5.1.2600]
    (C) Copyright 1985-2001 Microsoft Corp.

    C:\Documents and Settings\Administrator>cd c:\set PATH=c rogramFiles\Java\jdk1.
    6.0.05\bin;%PATH%
    The filename, directory name, or volume label syntax is incorrect.

    C:\Documents and Settings\Administrator>cd c:\Java Head First

    C:\Java Head First>set PATH=C rogram Files\Java\jdk1.6.0.05\bin;%PATH%

    C:\Java Head First>cd c:\Java Head First\sub


    C:\Java Head First\sub>javac DotCom.java
    DotCom.java:5: <identifier> expected
    private ArrayList<String> locationCells;
    ^
    DotCom.java:7: <identifier> expected
    public void setLocationCells(ArrayList<String>loc)
    ^
    DotCom.java:34: ')' expected
    }
    ^
    3 errors

    C:\Java Head First\sub>javac DotComBust.java
    DotComBust.java:5: <identifier> expected
    private ArrayList<DotCom> dotComsList = new ArrayList<DotCom>();
    ^
    DotComBust.java:21: ';' expected
    for (DotCom dotComToSet : dotComsList)
    ^
    DotComBust.java:26: illegal start of expression
    }
    ^
    DotComBust.java:25: ';' expected
    }
    ^
    DotComBust.java:40: ';' expected
    for (DotCom dotComToTest: dotComsList)
    ^
    DotComBust.java:54: illegal start of expression
    }
    ^
    DotComBust.java:53: ';' expected
    System.out.println(result);
    ^
    7 errors

    C:\Java Head First\sub>javac GameHelper.java
    GameHelper.java:17: ';' expected
    inputLine is.readLine();
    ^
    GameHelper.java:27: <identifier> expected
    public ArrayList<String>placeDotCom(int comSize)
    ^
    GameHelper.java:82: ';' expected
    }
    ^
    3 errors

    C:\Java Head First\sub>
    ***************************************************************************
    Here are the programs that caused this output, please bear in mind I am only using the text as writ, also I am not interested in finding fault with anyone, only to get through the book, which would be somewhat pointless if code don't work :-
    ***************************************************************************
    import java.util.*;

    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 sank" + name + " ");
    }
    else
    {
    result = "hit";
    }
    }
    return result;
    }
    }

    ***************************************************************************
    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)
    {
    ArrayList<String> newLocation = helper.placeDotCom(3);
    dotComToSet.setLocationCells(newLocation);
    }
    }
    private void startPlaying()
    {
    while(!dotComsList.isEmpty())
    {
    String userGuess = helper.getUserInput("Enter a guess");
    checkUserGuess( userGuess);
    }
    finishGame();
    }
    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;
    }
    }
    System.out.println(result);
    }
    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");
    }
    }
    public static void main (String args [])
    {
    DotComBust game = new DotComBust();
    game.setUpGame();
    game.startPlaying();
    }
    }
    *************************************************************************

    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.print(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();
    }
    public ArrayList<String>placeDotCom(int comSize)
    {
    ArrayList<String> alphaCells = new ArrayList<String>();
    String [] alphacoords = new String[comSize];
    String temp = null;
    int [] coords = new int [comSize];
    int attempts = 0;
    boolean success = false;
    int location = 0;
    comCount++;
    int incr = 1;
    if((comCount % 2 ) ==1)
    {
    incr = gridLength;
    }
    while (!success & attempts++ <200)
    {
    location = (int) (Math.random() * gridSize);
    int x = 0;
    success = true;
    while (success && x < comSize)
    {
    if (grid[location] ==0
    {
    coords[x++] = location;
    location += incr;
    if (location >= gridSize)
    {
    success = false;
    }
    if (x>0 && location % gridLength == 0)
    {
    success = false;
    }
    }
    else
    {
    success = false;
    }
    }
    }
    int x = 0;
    int row = 0;
    int column = 0;
    while (x < comSize)
    {
    grid[coords[x]] = 1;
    row = (int) (coords[x]/gridLength);
    column = coords[x] % gridLength;
    temp = String.valueOf(alphabet.charAt(column));
    alphaCells.add(temp.concat(Integer.toString(row)));
    x++;
    }
    return alphaCells;
    }
    }
    ***************************************************************************

    The above were written in notepad, so can be copied, saved as "xxx.java" and compiled, as per usual.
    Hoping you can help to get them compiler compliant, so I can play 'Sink a Dotcom' all by myself.
    Thanks.
    Yours
    Simon.
     
    author
    Posts: 9050
    21
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Hi Simon,

    One thing that I'm wondering is whether you're going through the book from the beginning? For instance, have you done all the exercises in the earlier chapters? By the time you get to chapter 5, things are pretty complex, so if you've skipped some of the earlier stuff that might be why you're struggling now.

    For instance, has your Java installation been used to successfully compile smaller programs? A really common approach to programming is to test things in small steps. So, for instance, after I've installed a new version of Java, I'll test it with a little 5 line program like this:

    public class Tester {
    public static void main(String[] args) {
    System.out.println("running on the new version of Java");
    }
    }

    When I read your posts it seems like maybe you're tackling two big issues at once:

    #1 - installing and configuring your Java environment
    #2 - testing a fairly substantial Java program

    It's really, really, really hard to debug problems when you're juggling so many variables at once.

    hth,

    Bert
     
    Campbell Ritchie
    Marshal
    Posts: 79922
    395
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Don't get your knickers in a twist.

    This is why I told you not to send the details in a private message; this is a public board where everybody learns from what is posted.
    What you posted does not throw the whole series of compiler errors you quoted.
    And what I downloaded from the O'Reilly website (HFJ) ten minutes ago compiles without problem, once you get the pacakage structure sorted out.

    We are trying our best to help.

    Bert Bates is right to try out a tiny program first, but it would have been better to writewhich actually contains a Java5-specific feature.

    You don't want your JDK environment in your classpath, you want it in your PATH. Did you do what I suggested at first ("javac -version")? What did it print out. If you have put JDK6 in the classpath and not in the path, then your problem is that you have installed Java incorrectly. That is the other thing Bert is hinting at. Make sure you have that correct, or nothing will work.

    Good luck with it.
     
    Campbell Ritchie
    Marshal
    Posts: 79922
    395
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    BTW: If you get a in your posting you have set the PATH wrongly using : then P. It should read :\P. Try again with C:\Program Files\etc\etc when you set your PATH. And make sure the last bit of your PATH to set is "bin".
    [edit]That last bit means you write ....bin before the %PATH% bit[/edit]
    [ March 30, 2008: Message edited by: Campbell Ritchie ]
     
    Greenhorn
    Posts: 2
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator

    Simon Evans wrote:Dear Programmers,
    I have been reading 'Head First Java' anyway, after a certain point, to run the programs therin it was necessary to install jdk 6.0, which I did, but I still get compiler error returns, even upon using code lifted directly from the headfirstlabs.com site. The book recommends this site (JavaRanch) to discuss whatever problems are thus encountered. I encountered such problems on pages 150 - 3, with the programs DotCom, DotComBust and GameHelper. They all return compiler errors, so I can't play the version of 'Battleships' as outlined.
    It seems even though I am using the jdk 6.0 - the compiler won't recognise the 'enhanced loops' nor other stuff - like 'input streams' - just like the jdk 1.2 didn't. I could go into greater detail as to the error returns, but would like to know if there is a sub-site in Java Ranch that might deal with this conumdrum.
    Thank you for your assistance.
    Yours
    Simon Evans



    the placeDotCom method maybe has some bug.I am not sure for I just glanced round.Too much lines -_-!
    I reviced the placedotcom method and give you some code for test.If you have no problem in Guess method,these code for placeDotCom may help you run the program correctly.

    >
     
    Ranch Hand
    Posts: 47
    Netbeans IDE Eclipse IDE Debian
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Hello Simons,

    The code of DotCom.java is fine, when I copy pasted it from this post in a TEXTFILE called DotCom.java. I knew that upfront, I suspected you where not using a plain text editor because of the error:


    I reproduced compiler errors when opening a textfile with wordpad and saving it as DotCom.java.

    So it looks like you are using wordpad or a simmilar textprocessor. Use notepad or even better use notepad++ (its free).

    regards,
    Ben




     
    Greenhorn
    Posts: 1
    • Mark post as helpful
    • send pies
      Number of slices to send:
      Optional 'thank-you' note:
    • Quote
    • Report post to moderator
    Thanks everyone for the clues, especially "once you get the package structure sorted out".

    Straight from the zip file (see wickedlysmart.com) it does almost work but only if you change the package names & file structure.
    Change the first line in chap05/GameHelper.java from
    package chap05;
    to
    package helpers;

    Also within chap06/DotComBust.java remove (or comment out) the first line
    package chap06;

    Put both of those .java files in your root directory (wherever the rest of your .java files are).
    And this is the important bit, which hasn't been covered in the book yet (I'm sure it will be, but not yet)
    - put the GameHelper.java file within a "helpers" folder before you compile it. Because the line "import helpers.GameHelper;" within DotComBust.java expects it to be in a folder called "helpers".

    Like magic, all three files compile & the game runs


    Good book by the way. Looks like it's designed for teenagers but it really does keep me interested. Cheers, nick
     
    It is difficult to free fools from the chains they revere - Voltaire. tiny ad:
    Gift giving made easy with the permaculture playing cards
    https://coderanch.com/t/777758/Gift-giving-easy-permaculture-playing
    reply
      Bookmark Topic Watch Topic
    • New Topic