Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I can't get this to work, methods & instance variables

I'm new to programming, I'm sorry if this is a silly mistake, but I keep getting this error "CompanyAddress.java:11: error: cannot find symbol System.out.println(testObject.getName(CompanyName));" I don't know what I'm doing wrong.

The main.

import java.util.Scanner;
public class CompanyAddress
{
  public static void main(String[] args)
  {
     Scanner scan = new Scanner(System.in);
     test testObject = new test();
     System.out.println("Enter name: ");
     String input = scan.nextLine();
     testObject.getName(input);
     System.out.println(testObject.getName(CompanyName));
  }
}   

my test.java

import java.util.Scanner;
public class test 
{
    String Name;

    public String getName(String CompanyName) 
    {
        Name = CompanyName;
        return Name;
    }


}
like image 372
Waj Avatar asked Nov 24 '12 17:11

Waj


3 Answers

First of all you need to declare your variable companyName, before passing it to your method.

Secondly, your method: -

public String getName(String CompanyName) 
{
    Name = CompanyName;
    return Name;
}

Seems strange to me. You are using the same method as getter and setter.

You should have separate setter and getter: -

public void setName(String companyName) {
    name = companyName;
}

public String getName() {
    return name;
}

And invoke them separately.

testObject.setName(companyName);

System.out.println(testObject.getName());

Just a suggestion: -

Follow Java Naming Convention. Field names and method names should start with lowercase alphabet.

like image 61
Rohit Jain Avatar answered Sep 28 '22 18:09

Rohit Jain


System.out.println(testObject.getName(CompanyName));

What CompanyName this here? It is not known symbol. It could be System.out.println(testObject.getName("CompanyName"));

or

String CompanyName ="name";
System.out.println(testObject.getName(CompanyName);
like image 24
Subhrajyoti Majumder Avatar answered Sep 28 '22 19:09

Subhrajyoti Majumder


You have to declare the variable CompanyName. Something like this:

String CompanyName = "CompanyName1";
System.out.println(testObject.getName(CompanyName));

Since you are modifying a variable you should do:

public class test
{
       String Name;

        public void setName(String CompanyName) {this.Name = CompanyName;}

        public String getName()                 {return Name;}

}

The method getName will return the name of the "Company" and the setName will modify the name of the "Company". This way you can separate different concerns.

Furthermore, you can in the future call the method getName without modifying the actual name of the company.

like image 20
dreamcrash Avatar answered Sep 28 '22 19:09

dreamcrash