Java: cannot find symbol error - java

I'm taking an intro Computer Science class at university and on our second assaignment I've been getting an error of "Cannot find symbol" when i try changing the stuudent3's name. If I take the statement out it will get up to 75% but then read the error "compile error: changeName method not called properly." Though maybe you guys could help me out and explain to me what is wrong. Thanks in advance!
student3 = student3.changeName(Bill);
(This is where I get the error, Bill is underlined in red and it stats that it cannot find the symbol.)
I'm currently using netbeans if that changes anything.
import ProvidedClasses.Student; // Necessary! Do Not Remove!
public class Question1
{
/*
1) Declare 3 Student object references (variables) with the identifiers student1, student2, and student3
2)
Use the default constructor method of the Student class to instantiate an Student object and assign it to
the student1 object reference (variable)
3) Use the alternate constructor method of the Student class to instantiate a Student object by passing the followin arguments:
First, the String literal "Richard Rosby"
Then, a non-negative integer literal of your choosing
Assign that object to the object reference student2
4) Assign the object reference student3 the value of the object reference Student2
5) Declare 2 String objects oldName and newName
6) Assign oldName the value returned by a method call to the getName method for the student2 object
7) Call the changeName method on the student3 object and pass your own choice of a new name as an argument
8) Assign newName the value returned by a method call to the getName method for the student3 object
*/
public static Object[] question1()
{
// Your Code Goes Here
Student student1 = new Student();
Student student2 = new Student("Richard Rosby", 23);
Student student3 = student2;
student3 = student3.changeName(Bill);
String oldName = student2.getName();
String newName = student3.getName();
// Necessary for Unit Test. Do not remove or modify!
return new Object[] {student1, student2, student3, oldName, newName};
}

Student's constructor accepts a java.lang.String. Assuming you intended to use the literal "Bill", you should surround it with quotes (") - otherwise java interprets it as a variable name, which was of course never declared:
student3 = student3.changeName("Bill");

Perhaps it should be student3.changeName("Bill"); with the double quotes.
Without the double quotes, Java thinks you are using an object or class.
EDIT:
By taking into account the new error you get (Regarding Incompatible types), the problem seems like the method changeName is not returning any thing.
So simply remove student3 = from the statement student3 = student3.changeName("Bill");, that should solve the problem.

Related

When exacty is the object initialized?

I want to ask you when is the exact moment when an object is initialized
For example I have this simple Java code:
public class Test {
public static void main(String args[]) {
Student student = new Student();
student.setName("John");
student.setId(123);
}
}
So when exactly is the student object initialized? Is it initialized when new Student() is executed? Or when Student student = new Student() is executed? Or after setters are executed? Any feedback will be appreciated!
It's initialized when new + constructor is called.
As states the docs
Each of these statements has three parts (discussed in detail below):
Declaration: The code set in bold are all variable declarations that
associate a variable name with an object type.
Instantiation: The
new keyword is a Java operator that creates the object.
Initialization: The new operator is followed by a call to a
constructor, which initializes the new object.
Is it initialized when new Student() is executed?
Yes. When the resulting object is returned, it has been initialized (by the constructor code).
Or after setters are executed?
The fields of the object are initialized by the time the constructor returns. They may be set to null or "" or 0 or similar, but they're initialized with some value.
If it's not valid for a Student object to have null or whatever for those fields, then the constructor should accept the values for them as parameters, or the class should expose a builder-style interface for building an instance, so that by the time you have a Student instance, you know the fields are filled in with meaningful values. Whether that's necessary is domain-specific.
It depends on your constructor class. Probably line three, but if your mutator methods create new objects then line 4 and 5.
It get initialized when new Student() is executed.
new Student() - this calls the constructor of the Student Class.
After that, the resulting object is assigned to the 'student' variable where the data type is Student.
Whenever 'new' keyword is invoked, the object is instantiated and the constructor is called resulting in object initialization.
First of all, see the difference between a setter and constructor and their pros and cons.
Constructor:
1) A constructor is called when an object is created.
2) They are only called once per object.
3) You may use the constructor to set values at the point of instantiation.
4) It does not allow any return type.
5) A constructor is invoked implicitly.
Setter:
1) A setter is called to change the value of the object after it was initialized.
2) A setter can be called any number of times.
3) You may use the setter to set values after the point of instantiation.
4) It allows return type.
5) A setter is invoked explicitly.
Conclusion:
1) Object is initialized when new Student() is executed
2) Use constructor if you think initialization is mandatory and you have the required values before you can use the object.
3) Use the setter method when the initialization of the variable is non-mandatory and you don't have the values at the time of object initialization.
4) Generally, we should avoid setter as it somehow violates the principle of encapsulation.
Student student = new Student();
When you call new and then the constructor you are creating an object of the same type of your constructor class, the object that is receiving the new + constructor must be the same type.
Another example:
Object that must be the same as your class + name of the object signal = then new plus constructor;
Example exaple = new Example();
When you call
Student student = new Student();
you are creating an object in memory. Once created, you can use the object's methods, like getters and setters.

Referencing objects to arraylist [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
Hi I'm unsure how I go about referencing objects to my arraylist.
The class where im declaring the arraylist:
Any help would be much appreciated
First of all name is not static so you can not access it as Student.name only instance of student can access it if it's public.Now, you want to construct the Student than you should pass the name of student in constructor.You can declare getter and setter methods for your Student attributes.
Moreover ArrayList.add can be used to add your Students to your list and you better not add students in constructor use different method to write this scenario.
FOR EXAMPLE :
Student student = new Student("NewStudent");
System.out.println("Name of student :" +student.getName());
studentList.add(student);
Regarding:
public TutorGroup() {
super();
Student student = new Student(Student.name); // this makes no sense
studentList.add(student.Student(name, tmaMark));
}
I'm not sure what you're trying to do with new Student(Student.name) since it isn't clear what this code is trying to do, but regardless, the compiler is right -- it shouldn't exist, and so get rid of it.
Delete this TutorGroup constructor and re-do it. How you re-do it will depend on where your TutorGroup is to get the Student objects. If they're going to be packed into an ArrayList and then passed in, then give TutorGroup's constructor an ArrayList<Student> parameter, and when calling the class, pass in the list. If you will add Students one at a time, then make the constructor simple (or get rid of it), and give the TutorGroup class an addStudent method:
public void addStudent(Student s) {
studentList.add(s);
}
In your TutorGroup constructor your trying to pass the value in the name variable in the Student class which you cant access because 1. The name variable is private so only members of the class have access to it. and 2. It doesn't hold a value yet since that's what your trying to pass into the Student constructor.
What you should do is pass a string literal into your Student constructor like: new Student("Jamie") then it will be saved in the name variable in your Student class, and if you need to access the name later add a public method in your Student class that returns the value in your name variable.
Your code has several issues.
Firstly the Student class should have some getter methods, so that you can access the data from a student object:
public String getName() {
return this.name;
}
public int getTmaMark() {
return this.tmaMark;
}
For creating a student object with the correct data, you have 2 options:
Option A) Create a constructor for Student that takes both values:
public Student(String aName, int aMark)
{
super();
this.name = aName;
this.tmaMark = aMark;
}
Option B) Create setters for your Student class
public void setName(String aName) {
this.name = aName;
}
public void setTmaMark(int aMark) {
this.tmaMark = aMark;
}
You can, of course, implement both options in Student, giving you extra flexibility.
Then, to add a new Student to your ArrayList, you can simply create a student and use the array's add method:
Examples:
ArrayList<Student> studentList = new ArrayList<Student>();
// Create student using constructor
Student studentA = new Student("Alice", 15);
// Create student using setters
Student studentB = new Student();
studentB.setName("Bob");
studentB.setTmaMark(10);
// Add both students to the ArrayList
studentList.add(studentA);
studentList.add(studentB);
Please remeber that for the studentB example, if you added a constructor with arguments to your Student class (Option A) you also need to create an explicit default constructor (without arguments).
Im not sure exactly what you are trying to do. I am going to assume you want to add a student into the ArrayList called student list. The line Student student = new Student(Student.name); is creating a new object of type Student called student but you are not passing into any parameters into the constructor for the student class, but it requires a String which is used as the name. What you want to do (i think) is add a student to your array list. As your ArrayList has type student the method to add student x should be
public void addStudent(Student x)
{
studentList.add(x);
}
Where Student x is passed as a paramater to the addStudent method. To Create a new student with the object name newstu and the name nameOfStu you could do this.
Student newstu = new Student(nameOfStu);
addStudent(newstu);
I hope this helps.

Java bicycle and bicycle test

I have a problem to write my code. This is a code where I have to create an object class and run it using another class object.
The program is called bicycle and bicycletest.
I was given the bicycle program (its already been written) and all I need I write bicycletest to utilize the bicycle.
Now, the problem is, i have created 2 object, called NiceBicycle and CoolBicycle. I need to change my NiceBicycle name to "Kenny McCormick, but i cant do it. i keep getting error saying
"error: variable NiceBicycle might not have been initialized" for this line of command that i write.
// Change the owner's name to Kenny McCormick using setOwnerName
NiceBicycle.setOwnerName("Kenny McCormick");
what should i do?
anyway, here is the bicycle code, and bicycletest that i write based on the instructor command.
Thank you for your reply
bicycle.java
public class Bicycle
{
// Instance field
private String ownerName;
private int licenseNumber;
// Constructor
public Bicycle( String name, int license )
{
ownerName = name;
licenseNumber = license;
}
// Returns the name of this bicycle's owner
public String getOwnerName()
{
return ownerName;
}
// Assigns the name of this bicycle's owner
public void setOwnerName( String name )
{
ownerName = name;
}
// Returns the license number of this bicycle
public int getLicenseNumber()
{
return licenseNumber;
}
// Assigns the license number of this bicycle
public void setLicenseNumber( int license )
{
licenseNumber = license;
}
}
and here is bicycletest.java that i wrote.
public class BicycleTest
{
public static void main( String[] args )
{
// Create 1 Bicycle reference variable. For example: myBike
Bicycle NiceBicycle;
// Create 1 String reference variable for the owner's name
String name;
// Create 1 integer variable for license number
int licenceNumber;
// Assign your full name and a license number to the String and
// integer variables
name = "Boo Yeah";
int licenseNumber = 9972;
// Create a Bicycle object with the Bicycle class constructor
// Use the variables you created as arguments to the constructor
Bicycle CoolBicycle = new Bicycle( "Boo Yeah", 9972 );
// Output the owner's name and license number in printf statements
// using the object reference and the get methods.
// For example: bike.getOwnerName()
System.out.printf ("The CoolBicycle owner's name is %s\nThe license number is %d\n", CoolBicycle.getOwnerName(), CoolBicycle.getLicenseNumber());
// Change the owner's name to Kenny McCormick using setOwnerName
NiceBicycle.setOwnerName("Kenny McCormick");
// Output the owner's name and license number in printf statements
// using the Bicycle object reference variable and the get methods.
System.out.printf ("The NiceBicycle owner's name is %s\n", NiceBicycle.getOwnerName());
}
}
You need to instantiate Bicycle and assign it to NiceBicycle in your test by changing:
Bicycle NiceBicycle;
to:
Bicycle NiceBicycle = new Bicycle("", 0);
Then you can setOwnerName() on it:
NiceBicycle.setOwnerName("Kenny McCormick");
Also, note that Java conventions suggest that variable names start with lowercase letters, so NiceBicycle should really be niceBicycle if you want to follow Java conventions.
NiceBicycle hasn't been initialised (the bicycle object hasn't been created).
Try replacing
Bicycle NiceBicycle;
With
Bicycle NiceBicycle = new Bicycle("",0);
The compiler is being kind. You didn't set NiceBicycle before trying to use it. The variable is not set.
Also note that the Java convention is to always name variables starting with lower case, and classes starting with upper case. This is important because . is heavily overloaded, that is, it dues many different things.
you need to initalize your NiceBicycle object.
Bicycle NiceBicycle = new Bicycle( "Some value", 9972 );
Try something like this
Bicycle NiceBicycle = new Bicycle("User2", 0);
Then try to change the name of the owner
You are having just a reference to a Bicycle object
Bicycle NiceBicycle;
Therefore actual Bicycle instance haven't created yet in the memory.
Before you are setting the name you must create an actual instance first. Then try to set the name.
Bicycle NiceBicycle = new Bicycle(null, 0);
NiceBicycle.setOwnerName("Kenny McCormick");
Andy you have created the constructor for Bicycle class that will set the name of Owner and licenseNumber. Ever time you create an object you use new keyword. As it performs some operations i-e 1 it will call the default constructor or overloaded constructor according to values you gave 2 it allocates the memory. That is why when you create an object of class you use new keyword now you are getting error because you have not properly initialized the object to initialize it you will do it as Bicycle NiceBicycle = new Bicycle("",0); now to set values you will call its Setter and Getter methods like thisNiceBicycle.setOwnerName("SetName") now to get name you will call as string OwnerName = NiceBicycle.getOwnerName()

I am getting unusual object reference codes and null values when I initialise a constructor

I have a couple of questions about how class instances are set up. If I have an object constructor as follows:
Object(String newName, ArrayList<Person> newPersonList){
name=newName;
personList=newPersonList;
System.out.println(personList);}
which is then assigned to a person as a method in the Object class:
matchPersonToObject(Person person){
this.matchedPerson=person;
person.addToObjects(this); //do I need to add the full project.domain address in here?
//Because if so it will only let me put the class `Person` in rather than an instance `person`
}
//in the person class:
addToObjects(Object obj){
this.objectList.add(obj);
System.out.println(objectList);
}
when I then initialise this as follows:
Person chris=new Person("Chris");
Object obj1=new Object("thing",new ArrayList<Person>(Arrays.asList(chris)))
it gives an output of:
[project.domain.Person#1a40fff] //personList in object constructor
[Object - null] //objectList once person has been matched to it
My two questions are
a) what is that hexidecimal code that is being give to my person instance? Why does it not just display [project.domain.chris]?
b)When I add the object to the objectList, why is this registering as null? Have I initialised the ArrayList correctly?
First: Never name your classes with reserved words of languague you are using, e.g. avoid create classes with names like Vector, Long, etc... generates confuse in your code.
Second: he hexidecimal code you are looking at is the hash code of your class Person, overwrite the method toString() os Person class.
public String toString() {
return <anything_you_want> + name;
}
it's possible a bad package importation because you have a class with Name object and compiler doesn't recognize your class, java.lang.Object is different of your Object class.

Polymorphic behavior not being implemented

The last two lines of this code illustrate the problem: the compiler works when I use the reference to the object, but not when I assign the reference to an array element. The rest of the code is in the same package in separate files. BioStudent and ChemStudent are separate classes, as well as Student.
package pkgPoly;
public class Poly {
public static void main(String[] arg) {
Student[] stud = new Student[3];
// create a biology student
BioStudent s1 = new BioStudent("Tom");
// create a chemistry student
ChemStudent s2 = new ChemStudent("Dick");
// fill the student body with studs
stud[0] = s1;
stud[1] = s2;
// compiler complains that it can't find symbol getMajor on next line
System.out.println("major: " + stud[0].getMajor() ); // doesn't compile;
System.out.println("major: " + s0.getMajor() ); // works: compiles and runs correctly
}
}
There's a lot of missing info, such as what is s0, or if BioStudent and ChemStudent extend Student, however I'll just assume all of this is true and s0 is either a BioStudent or ChemStudent.
If so, I'm not entirely sure about the proper terminology, but when you use a reference variable of the parent type and point it to a Child object, you can only access the child methods if these override the parent methods.
In other words, you need to have the getMajor() method defined in your parent class Student, then overriden in your child class BioStudent and/or ChemStudent.
stud is an object of class Student.
I am assuming few things -
BioStudent and ChemStudent extends Student class.
BioStudent has a method getMajor()
Student Class does not!
That is the reason stud[0].getMajor() is giving you a compile time error.
You have to typecast it to the subclass of Student.
System.out.println("major: " + ((BioStudent) stud[0]).getMajor() );
According to the information given I am assuming couple of things.
Student is a super class
BioStudent and ChemStudent extends Student
stud[0] = s1
stud[1] = s2
The error that you are getting is because Student class doesnt have getMajor() but the BioStudent and ChemStudent has that method.
You have created a Student array. For the compiler stud[0] is Student class, not the BioStudent nor ChemStudent. Only during the runtime jre would know that stud[0] has BioStudent and stud[1] has ChemStudent. That is why you are getting the compilation error.
Solution 1:
Either add getMajor() method to Student class and the other 2 class overrides it.
OR
Solution 2:
Typecast by adding this to your print statement (BioStudent stud[0]).getMajor() - which explicitly means this is BioStudent object and the compiler would know BioStudent has getMajor().

Categories