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;
}
}
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.
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);
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With