Cannot find Symbol error in Java - why? - java

I am having a hard time understanding the object oriented world. I am working on a homework assignment and I can't understand why I am getting an error here. The issue I am having is in the add method. I am using the Netbeans IDE (per professor requirement) and the problem I am getting is in the add method. There are two errors that both say "Cannot find Symbol"; one is in reference to the variable customers while the other is in reference to the variable numCustomer. I am trying to understand what I am doing wrong, not just how to fix it.
What I have so far:
package homework6;
/**
*
* #author christian
*/
public class Homework6 {
// Declare variables
private int numCustomers = 0;
private Customer customer;
// Constructor
public Homework6() {
Customer[] customers = new Customer[50];
}
/**
* #param args the command line arguments
*/
public void main(String[] args) {
System.out.println("Christian Beckman N00963294");
System.out.println("Homework 6");
System.out.println(); // Prints a blank line
// Create and instance of Homework6
Homework6 homework6 = new Homework6();
homework6.execute(args);
}
private void add(Customer customer) {
int i = 0;
customers[i] = customer;
i++;
numCustomer++;
}
private void displayCustomers() {
}
private void execute(String[] args) {
}
private int getTotal() {
}
private void readFile(String filename) {
}
}

Your variable is numCustomers with an 's' but your method refers to numCustomer++; without an 's'.
It should be:
numCustomers++;
For
private Customer customer;
it should probably be:
private Customer[] customers;
Be very careful in your code where you refer to customer and customers. It looks like you are using the convention "customer" for just one and "customers" for the array. If that is too subtle for you then consider changing to something like oneCustomer and allCustomers.

You create an array of Customer objects in the constructor, then the array is immediately destroyed. Try declaring it like this:
public class Homework6 {
// Declare variables
private int numCustomers = 0;
private int i = 0;
private Customer customer;
private Customer[] customers;
// Constructor
public Homework6() {
customers = new Customer[50];
}
...
The reason for this, is any variables declared inside a method (in this case, the constructor) has something called local scope which means it can ONLY be accessed inside that method. The variables you declare outside the methods have something called global scope, which means that variable can be accessed across all the methods in a class.
For the same reason as above, i will keep resetting to 0 each time you call the add function. To fix that, declare private int i = 0 above the constructor with the other variables. Then write the method like so:
private void add(Customer customer) {
customers[i] = customer;
i++;
numCustomers++;
}
Also, whenever you do numCustomer++ in the add method, you should put numCustomers++ like above because you declared numCustomers with an 's' at the end. Has to match EXACTLY.

Related

using two classes in java

I am trying to use two classes Member class and Website class to talk to each other. I want to use the code which is in the setloggedInStatus() method in the Member class and be able to use it in the memberLogin() method which is in the Website class. I used the Member memberObject = new setloggedInStatus(); code but its giving me an error.
I Would appreciate any help. Thanks in advance
Website class
public class Website
{
// declaration of vars
private String websiteName;
private int hits;
private double salesTotal;
/**
* Constructor for objects of class Website
*/
public Website(String websiteName)
{
// initialise instance variables
this.websiteName = websiteName;
}
Member memberObject = new setloggedInStatus();
public void memberLogin() {
}
}
Member class
public class Member
{
// varibales declaration
private String email;
private int membershipNumber;
private boolean loggedInStatus;
/**
* Constructor for objects of class Member
*/
public Member(String memberEmail, int newMembershipNumber )
{
// initialise instance variables
email = memberEmail;
membershipNumber = newMembershipNumber;
}
//loggedInStatus method
public void setloggedInStatus() {
if (email != null && membershipNumber != 0) {
loggedInStatus = true;
System.out.println("you are logged in ");
}
else {
loggedInStatus = false;
System.out.println("you are not logged in");
}
}
}
If you wanted to use the functionality of Member inside the class Website, you would need to import it via import Member at the top of the Website file (depending on if they're in the same folder/package). This will make it available inside the file.
You could then create a new Member object via Member member = new Member(params go here);
Then, you could call the methods contained inside your Member class from your created member object, for example member.setLoggedInStatus();
EDIT: Did this answer your question?
if the Website Class and the Member Class are in the same package you have to create an object of Member like this:
String email = "Example#examplemail.com";
int id = 3; //Example id
Member the_member = new Member(email,3);
If you want to call the public void setloggedInStatus() method you can simply do something like this with the previous object created:
the_member.setloggedInStatus();
If the two classes are not in the same package you have to import the class Member with
import Member

How do you add to an ArrayList using generics?

I'm struggling with an assignment of mine and I can't figure out how to add another element to my list.
import java.util.ArrayList;
public class Ballot {
private ArrayList<Candidate> ballot;
private String officeName;
public Ballot(String officeName) {
this.officeName = officeName;
ArrayList<Candidate> ballot = new ArrayList<Candidate>();
}
public String getOfficeName() {
return officeName;
}
public void addCandidate(Candidate c) {
ballot.add(c);
}
public ArrayList<Candidate> getCandidates() {
return ballot;
}
public static void main(String[] args) {
Ballot b = new Ballot("Election");
b.addCandidate(new Candidate("Sarah", "President"));
System.out.println(b);
}
}
When I try to run the document, it throws a NullPointerException. What am I doing wrong?
The constructor initializes a local variable named ballot that hides the data member with the same name. Then, when you try to add to it, it fails with a NullPointerException, since it was never initialized. If you initialize it you should be OK:
public Ballot(String officeName) {
this.officeName = officeName;
ballot = new ArrayList<Candidate>(); // Here!
}
You're not initializing your list of candidates properly in the Ballot constructor. You need to do:
this.ballot = new ArrayList<Candidate>();
Right now you're just creating a local variable named ballot in the constructor which shadows the actual class field. Since it has never been initialized, you end up getting a NullPointerException when you eventually try to add an element to it.
Also, as a best practice, use interfaces instead of the concrete type. This makes it easy to change implementations later. So instead of defining the field as private ArrayList<Candidate> ballot;, define it as private List<Candidate> ballot;.
As simple that you are not using this object. You are never initiliazing your object
Correct way
public Ballot(String officeName) {
this.officeName = officeName;
this.ballot = new ArrayList<Candidate>();
}
You're overriding your class variable with a local variable of the same name. Either initialize the list directly
private List<Candidate> ballot = new Arraylist<>();
or initialize it in the constructor with
ballot = new ArrayList<>();
FYI: You shouldn't assign implementation classes for your local variables and return values if you can help it. "ballot" should just be the List interface as should the getter. That way if you ever want to change the implementation, you don't have to change everything. It could be an ArrayList, LinkedList, Stack, Vector, etc and it won't matter because they're all using the List interface.

Best way to set an erray to empty within the parameters of another class

This class is where I want to call the arrays and set the arrays to empty within the parameters
public class ElectronicsEquipmentSupplier {
private int currentMonth;
private int currentYear;
private String rangeOfProducts;
private CustomerDetailsList details; //Contains the customer details array
private PurchaseOrderList pal; //Contains the purchase array
public ElectronicsEquipmentSupplier(int currentMonth, int currentYear,
String rangeOfProducts ) {
this.currentMonth = currentMonth;
this.currentYear = currentYear;
this.rangeOfProducts = rangeOfProducts;
}
}
This is the class where the array is created. It pulls information from a separate class called PurchaseOrder and then sets the list.
public class PurchaseOrderList {
private ArrayList<PurchaseOrder> purchaseCollection;
public PurchaseOrderList() {
purchaseCollection = new ArrayList<PurchaseOrder>();
}
The CustomerDetailsList class is essentially the same. Just not sure as to the best way to set the array to empty when called in the ElectronicsEquipmentSupplier.
Simply wrap the collection's own clear() method with a publicly-accessible method in your PurchaseOrderClass:
public class PurchaseOrderList {
private ArrayList<PurchaseOrder> purchaseCollection;
public PurchaseOrderList() {
purchaseCollection = new ArrayList<PurchaseOrder>();
}
//THIS IS THE IMPORTANT PART
public void clearPurchaseCollection() {
purchaseCollection.clear();
//You could also accomplish the same thing by reinitializing the list:
//purchaseCollection = new ArrayList<PurchaseOrder>();
}
}
Note however, that calling new PurchaseOrderList() already guarantees an empty purchaseCollection list, since you initialize it in the constructor that way.
So the only time you would need to call clearPurchaseCollection() is if you are reusing this object and want to clean it out first. Depending on the rest of your application, that may be necessary, but it may also just be simpler to throw away that instance and create a new PurchaseOrderList(). Totally depends on the situation.

Changing object parameter with event handler

I'm trying to create an object and add it to an array I created as a parameter GUI object I constructed. For some reason I keep getting TheDates cannot be resolved to a Variable.
Object being constructed:
public static void main(String[] args)
{
DateDriver myDateFrame = new DateDriver();
}
//Constructor
public DateDriver()
{
outputFrame = new JFrame();
outputFrame.setSize(600, 500);
outputFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String command;
Date [] theDates = new Date[100]; //this is the array I am having issues with
int month, day, year;
...
}
This is where my problem with theDates is:
public void actionPerformed(ActionEvent e)
{ //The meat and Potatoes
if ( e.getSource() == arg3Ctor)
{
JOptionPane.showMessageDialog(null, "3 arg Constructor got it");
int month = Integer.parseInt(monthField.getText());
int day = Integer.parseInt(dayField.getText());
int year = Integer.parseInt(yearField.getText());
theDates[getIndex()] = new Date(month, day, year);//here is the actual issue
}
}
I don't know if I'm over thinking it or what, I've tried making the array static, public, etc. I've also tried implementing it as myDayeFrame.theDates.
Any guidance is greatly appreciated
You likely have a scope issue. theDates was declared in the constructor and is visible only in the constructor. A possible solution: declare it as a class field. Sure initialize it in the constructor, but if it is declared in the class, it is visible in the class.
You are defining theDates as local variable in the constructor, thus its scope is limited within the constructor. Instead, declare it as a field of the class:
private Data[] theDates;
// ...
public DateDriver()
{
theDates = new Date[100];
// ...
}
1. You have defined theDates, which is an Array Object Reference Variable inside the Constructor, so its having its scope inside the Constructor itself.
2. You should declare the theDates at the class scope, so it will be visible throughout inside that class.
3. And it will be better if you use Collection instead of Array, go for ArrayList
Eg:
public class DateDriver {
private ArrayList<Date> theDates;
public DateDriver() {
theDates = new ArrayList<Date>();
}
}

Accessing Instance Variables from Another Class

If you want to get straight to the problem, skip this paragraph. As practice, I am trying to write a Java program that simulates an economy, and to that end wrote a company class. The idea was to have, say, a dozen of them, wrap their earnings into a normalvariate function, and that would be the economy.
I wrote a separate class to graph the companies' outputs using JFreeChart. However, I can't access the ArrayList that I write the amount of money for each year to from the graphing class. I understand the best way to do this is probably with getters, but it didn't seem to work, so if that is your advice, could you please provide an example? Thanks!
The company:
public class ServiceProvider implements Company {
//Variables
public ArrayList getRecords(){
return records;
}
public ServiceProvider(){
money = 10000;
yearID = 0;
goodYears = 0;badYears = 0;
records = new ArrayList();
id++;
}
public void year() {
yearID++;
if(!getBankrupt()){
spend();
}
writeRecords();
}
public void spend() {
...
}
public void printRecords() {
for(int i=0;i<records.size();i++){
String[] tmp = (String[]) records.get(i);
for(String a:tmp){
System.out.print(a+" ");
}
System.out.print("\n");
}
}
public void writeRecords(){
String[] toWrite = new String[2];
toWrite[0] = String.valueOf(yearID);
toWrite[1] = String.valueOf(money);
records.add(toWrite);
}
public void writeRecords(String toWrite){
String temp = "\n"+yearID+" "+toWrite;
records.add(temp);
}
public boolean getBankrupt(){
boolean result = (money < 0) ? true : false;
return result;
}
}
What I am trying to access it from:
public class grapher extends JFrame {
ArrayList records = s.getRecords();
public grapher(){
super("ServiceProvider");
final XYDataset dataset = getCompanyData();
}
private XYDataset getCompanyData(){
XYSeries series;
for(int i=0;i<s.getRecords().length;i++){ //S cannot be resolved, it's instantiated in the main class.
}
}
}
The main class:
public class start {
public static void main(String[] args) {
ServiceProvider s = new ServiceProvider();
for(int i=0;i<10;i++){
s.year();
}
s.printRecords();
}
}
P.S. Don't tell me what a mess Records are. I know.
Pass the instance of ServiceProvider as an argument to the grapher constructor and then it can pass it as an argument to getCompanyData().
Since the instance is created outside of the grapher class, there is no way for grapher to have the instance of ServiceProvider to work with unless you hand that instance to grapher.
BTW, make sure that whatever you do with that ArrayList in grapher that you don't change it. If you do, you'll be changing it in the ServiceProvider (since it's all just references to the same underlying ArrayList). That's probably not what you want to do. If you do need to change it, make a copy and work with the copy.
Your grapher class is trying to use a variable from the start class(you are making calls to variable s which exists in the start class), without having a reference to the variable. In order for grapher to access that instance, you'll have to pass it in to the grapher class as a paramater in the constructor:
public grapher(ServiceProvider serviceProvider) {
records = serviceProvider.getRecords();
}
In the getCompanyData method, use your class variable records instead of s.
Your grapher class should be as follows
public class grapher extends JFrame {
public grapher(ServiceProvider s){
super("ServiceProvider");
final XYDataset dataset = getCompanyData(s);
}
private XYDataset getCompanyData(ServiceProvider s){
XYSeries series;
for(int i=0;i<s.getRecords().length;i++){
// Do Process of business logic.
}
}
}

Categories

Resources