Results 1 to 3 of 3
  1. #1
    boy22 is offline Member
    Join Date
    Jul 2007
    Posts
    36
    Rep Power
    0

    Default problem with a simple java code

    I'm doing a simple java program, when I try to compile it, the eclipse says that age isn't initialized
    this is my code, please check it out
    Java Code:
    public class First
    {
    
    
    public void calculate()
    {
    int age;
    
    if(age!= 0)
    {
    System.out.println(age)
    }
    
    else
    {
    System.out.println("you can't enter 0 as age")
    }
    }

  2. #2
    shanePreater is offline Member
    Join Date
    Jul 2007
    Location
    England, Bath
    Posts
    47
    Rep Power
    0

    Default

    yep the line where you have:
    Java Code:
    int age;
    This is simply showing the compiler that you will using a variable called 'age' and it is of type int but not what the actual age is you need to modify this line to something like:
    Java Code:
    int age = 29;
    This decalres it (as above) and then the = 29 bit sets age to be 29, obviously you can change this to any integer value you like.

    Hope this helps :D

  3. #3
    yiweiang is offline Member
    Join Date
    Aug 2007
    Posts
    15
    Rep Power
    0

    Default

    Hi,

    Shane Preater's method will solve this problem. But the importance of this issue is... variables declared inside of your methods ALWAYS need to be initialized before use. Otherwise a compiler error will result. However, that cannot be said for class variables. Those do not have to be declared before use.

    Yi Wei

Similar Threads

  1. Replies: 3
    Last Post: 12-12-2008, 12:12 PM
  2. problem while running java code..
    By Jjava in forum New To Java
    Replies: 0
    Last Post: 02-08-2008, 06:33 AM
  3. Peculiarty in code of simple program...
    By Kreuz14 in forum New To Java
    Replies: 4
    Last Post: 01-23-2008, 03:27 AM
  4. simple problem - code wont compile
    By dirtycash in forum New To Java
    Replies: 1
    Last Post: 11-20-2007, 05:49 PM
  5. simple code
    By elizabeth in forum New To Java
    Replies: 1
    Last Post: 08-07-2007, 06:49 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
  •