error: class, interface, or enum expected

  • (2 Pages)
  • +
  • 1
  • 2

16 Replies - 1008 Views - Last Post: 06 August 2013 - 07:19 PM Rate Topic: -----

#16 pbl  Icon User is offline

  • There is nothing you can't do with a JTable
  • member icon

Reputation: 8327
  • View blog
  • Posts: 31,857
  • Joined: 06-March 08

Re: error: class, interface, or enum expected

Posted 04 August 2013 - 09:34 PM

View Postfarrell2k, on 03 August 2013 - 11:57 PM, said:

Just initialize all local variables before referencing them. If you reference it, it MUST be initialized.

String answer2 = null;
answer2 = input.nextLine();


don't really need to set it to null if you assign a value the next time you access it
    String answer2 = input.nextLine();


will also do the job
Was This Post Helpful? 0
  • +
  • -

#17 streek405  Icon User is online

  • D.I.C Addict

Reputation: 10
  • View blog
  • Posts: 539
  • Joined: 10-March 13

Re: error: class, interface, or enum expected

Posted 06 August 2013 - 07:19 PM

View Postjon.kiparsky, on 03 August 2013 - 09:25 PM, said:

View Poststreek405, on 03 August 2013 - 11:06 PM, said:

View Postfarrell2k, on 03 August 2013 - 08:57 PM, said:

Just initialize all local variables before referencing them. If you reference it, it MUST be initialized.

String answer2 = null;
answer2 = input.nextLine();



This entire time I've been programming, I never really understood those keywords like initilaze. But now I think I get it:
if its pretty much not a constant (like a user input) then it must be written out all at once like
String answer = input.nextLine();


Am I right?



"Initialize" simply means that you give it a value to start with. In many languages, a variable will get a "default" value depending on its type, or else it will have a garbage value (whatever was left over in that piece of memory). It's always been considered good practice to overwrite the default immediately unless you actually know that it's the value you want - even then, many people will explicitly set it to that value, just to make the code more readable.
Java requires this initialization in many but not all cases. For example, when you initialize an array, you get its elements initialized for free. However, a naked String or other variable is initially unset, and it has to appear on the left hand side of an assignment before it can appear on the right hand side. (This initialization requirement is part of Java's reaction to the generally unsafe programming styles common in the '80s and '90s, which were mostly a result of smaller machines and tighter tolerances. Basically, by the time they were building Java it was obvious that we could afford to write safer code, and so they decided to require it)

In both of these examples, answer is set to the user input, so you're fine there.


Thank you for clearing that up for me! I got it now :D
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2