0

For a homework assignment, part of making the class that we use throughout the assignment requires me to create constructors that follow the guidelines

ContactInfo()

Default constructor and initializes a contact info with name = “unknown” and an empty list (length of zero)"

ContactInfo (String name, ArrayList<Phone> phoneNumber)

Constructor and initializes a contact info with the given name and the given list of phones."


This is our first assignment working with constructors and arraylists, and our textbook has little information on actually writing them as opposed to what they do.

This is what I've written so far.

import java.util.ArrayList;
import java.util.List;

public class ContactInfo {
    public String name;
    public ArrayList<Phone> phoneNums;

    public ContactInfo() {
        String name = "unknown";
        ArrayList phoneNumber = new ArrayList<Phone>(0);
    }

    public ContactInfo(String name, ArrayList<Phone> phoneNumber) {
        this.name = name;
        this.phoneNumber = phoneNumber;
    }
}

I am getting a "cannot find symbol variable phoneNumber" error, however I am pretty sure it is initialized and the method can access it. I am pretty confused on how to work constructors and complete the guidelines described at the top of the post. My professor is not willing to check his email over this Thanksgiving Break, so I cannot reach him for help.

Edit: We have another provided source file that is included with this code, however all the methods and variables are private (we aren't allowed to alter this file either), so I am not sure they will help.

Frontear
  • 1,150
  • 12
  • 25
  • 1
    You've got 2 glaring issues. First, your no parameter constructor isn't setting your fields, it's creating variables that can't be referenced. Second, you're trying to reference a `this.phoneNumber`, which doesn't exist in your class scope. `phoneNums` however, does exist. – Frontear Dec 01 '19 at 23:53
  • @Frontear Sorry, im a newbie with this stuff. How would I fix my no parameter constructor to set the fields instead of creating non referable variables? – Chillchaser Dec 02 '19 at 00:20
  • 1
    I'd recommend a java book or something. Nonetheless, if you want to refer to the class level variables, use `this.my_class_variable`. In your case, it would be `this.name`, and `this.phoneNums`. – Frontear Dec 02 '19 at 00:25

1 Answers1

0

You are trying to set a value to a variable(phoneNumber) that doesn't exist. this is a reference variable that refers to the current object. hence this is referencing to ContactInfo object in which phoneNumber doesn't exit.

You could do this

public ContactInfo(String name, ArrayList<Phone> phoneNumber) {
    this.name = name;
    this.phoneNums = phoneNumber;
}

Or

rename phoneNums to phoneNumber

Rahul Parihar
  • 52
  • 1
  • 9