• Post Reply Bookmark Topic Watch Topic
  • New Topic

Error in heaf first java?  RSS feed

 
Sjaak Hendriks
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, I'm trying to learn Java using the Head First Java book, but in one of the first assignments/examples I already get an error in my code.
So the error i get is: variable x is already defined, I fixed the error by removing int infront of x in the for method(code below).
My question is why would the author in the book have the int there if it gives you an error is this due the fact that at the time the book was written java 5 was the latest and now 7 is or am I doing something wrong?

Regards, Sjaak.


 
Ivan Jozsef Balazs
Rancher
Posts: 999
5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This example compiles with Java versions neither 1.4, 1.5, 1.6 nor with 1.7.
 
Ulf Lindqvist
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sjaak Hendriks wrote:
My question is why would the author in the book have the int there if it gives you an error is this due the fact that at the time the book was written java 5 was the latest and now 7 is or am I doing something wrong?


If you define x in an outer scope you cannot define x again in an inner scope. Then the definitions will clash. It's impossible to know which x you're referring to so the compiler will complain.

You can resolve it by not redefining x in the inner scope as you did. Then there's just the x in the outer scope and the compiler will know what x you're talking about. You can also simply use different names. For example x in the outer scope and i in the inner.

---

The reason the book got it wrong I guess is a typo that didn't get corrected. Maybe it is in later editions of your book.

It's quite common. Don't trust your life with what you read in books. And not with what you read at Java sites either.
 
Ulf Lindqvist
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
---
 
Sjaak Hendriks
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the replies, I just found it odd such a well recommended book would have an error like that, thats why I was second guessing myself, its even the 2nd edition.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!