Click here to Skip to main content
15,896,269 members
Please Sign up or sign in to vote.
2.00/5 (1 vote)
See more:
I'm getting error for the following Java code. I tried but unable to correct. Any help is appreciated. I started learning Java just a week ago.

C#
public class class1 {

    public static void main(String[] args) {


        int assigner()

        {
                int t = 7;
                return t;

        }


        int nom = assigner();
        System.out.println(nom) ;


    }

}
Posted
Comments
[no name] 22-Sep-14 11:25am    
Take your function declaration out of your main method.
Sergey Alexandrovich Kryukov 22-Sep-14 11:54am    
Do what Wes Aday suggested. Move assigner method out of main method.
When asking question, provide exact information on the error, especially — show in which line.
—SA
IAM_Dhruv 22-Sep-14 12:00pm    
Thanks. I also had to make the function declaration static. It worked. I will keep in mind the suggestion to give extra information about the error.
Sergey Alexandrovich Kryukov 22-Sep-14 16:10pm    
You don't have to make it static, but, in this very case, static is the most appropriate, because the function does not use "this" pointer (does not access any instance members). Code analyzers would mark this instance method as a minor performance leak. Do you understand that?

I hope you understand that this method is very redundant as it does next to nothing. Also, the name "assigner" would be misleading, as it does not assign anything, only its call may or may not assign. In practice, it would be much better to replace 7 (immediate constant) with explicitly declared constant.

—SA
IAM_Dhruv 26-Sep-14 23:05pm    
Got the point. I'm going through the concepts again. Thank you very much.

1 solution

As the solution is already given in the comments, here a clean code for that.
That might make things a little easier to understand.

Java
public class Project1 { // Class names always start with upper case! be careful with the wording, using keywords can ruin your day!
 
  public static void main(String[] args) {
    // create instance from class to break out of static context
    // 0 args constructor is always given, even if not written out
    Project1 project = new Project1(); 

    // call function from that class
    int nom = project.assigner(); 
    System.out.println("nom is: " + nom);
  }

  // private method, can only be used in this class
  private int assigner() 
  {
      int t = 7;
      return t;
  }
}


have fun!
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900