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>();
}
}
Related
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.
I need to use the variables from my constructor WinterCarnival() within my method update(). The update() method cannot have any parameters. I created an object of my FrozenStatue class in the constructor but I need to call a method from the FrozenStatue class from the update method. Essentially, I need to access frozStatObj01 within my update method.
public class WinterCarnival extends SimulationEngine {
public WinterCarnival() {
ArrayList<FrozenStatue> objects = new ArrayList<FrozenStatue>();
float[] fsObjPosition01 = new float[2];
fsObjPosition01[0] = 600;
fsObjPosition01[1] = 100;
float[] fsObjPosition02 = new float[2];
fsObjPosition02[0] = 200;
fsObjPosition02[1] = 500;
FrozenStatue frozStatObj01 = new FrozenStatue(fsObjPosition01);
FrozenStatue frozStatObj02 = new FrozenStatue(fsObjPosition02);
objects.add(frozStatObj01);
objects.add(frozStatObj02);
}
#Override
public void update() {
}
public static void main(String[] args) {
WinterCarnival wintCar = new WinterCarnival();
}
}
I assume it is the objects variable that you need to access from update().
What you need to do is to move this from a local variable to a field, e.g.:
public class WinterCarnival {
...
private ArrayList<FrozenStatue> objects;
public WinterCarnival() {
objects = new ArrayList<FrozenStatue>();
float[] fsObjPosition01 = new float[2];
fsObjPosition01[0] = 600;
fsObjPosition01[1] = 100;
float[] fsObjPosition02 = new float[2];
fsObjPosition02[0] = 200;
fsObjPosition02[1] = 500;
FrozenStatue frozStatObj01 = new FrozenStatue(fsObjPosition01);
FrozenStatue frozStatObj02 = new FrozenStatue(fsObjPosition02);
objects.add(frozStatObj01);
objects.add(frozStatObj02);
}
...
}
Now you can access objects from update().
PS. You should generally avoid concrete types in variable declarations in favor of the interfaces. In your case, use List instead of ArrayList:
private List<FrozenStatue> objects;
You can still initialize it as an ArrayList.
Dovetalk gave you the correct answer, but let me add an explanation.
You were using LOCAL variables ...
Local variables are declared in methods, constructors, or blocks.
Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
To have 'scope' (to be visible) to other methods in your class, you needed to use an INSTANCE variable (MEMBER variable in some other languages.)
Instance variables are declared in a class, but outside a method, constructor or any block.
This is what Dovetalk has done with your ArrayList object. Otherwise, it's only visible within the constructor, and is also destroyed once the constructor completes ... it was LOCAL only, just within the constructor. Dovetalk changed it to an INSTANCE variable. Then, it exists for the whole life of a WinterCarnival instance, and is visible to all the methods in the WinterCarnival class.
I hope that adds an explanation for you about what was going on there.
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.
I have a basic question in Java:
Consider I have
public void initialize(My_Class my_context) {
super.initialize(my_Context);
}
public void work(My_Class2 elt) {
String text = elt.getText();
My_Class3 var1 = new My_Class3();
String new_text = var1.my_method(text);
I am having a problem because I am calling the work method many times, and each time it instantiates a My_Class3 object, which takes a lot of time. I would like to move the instantiation in the initialize method so that it is performed once.
In order to do that, I tried to move
My_Class3 var1 = new My_Class3();
into initialize and set it as a global variable so that var1 is found in the different calls of work. However, I cannot set it into a static variable. I am guessing this has something to do with the visibility of the initialize method, but I cannot change it.
How can I instantiate a var1 variable of type My_Class3 in initialize and call it in work?
My_Class3 var1;
public void initialize(My_Class my_context) {
super.initialize(my_Context);
var1 = My_Class3();
}
public void work(My_Class2 elt) {
String text = elt.getText();
String new_text = var1.my_method(text);
}
The issue I'm having is, while I believe that I've have set up everything correctly in the constructor, when I try to call the instance variable from of my new Letter instance fromto I seem to keep getting an error saying that the compiler can not find variable fromto. The goal is to get Dylan to appear in with the Text.
public class Letter {
private String from; // Sets from instance variable to be stored
private String to; /// Sets to instance vaariable to be stored
public Letter(String from, String to) {
this.from = from;
this.to = to;
}
public Letter() {
Letter fromto = new Letter("Dylan", "April");
}
public static void main(String[] args) {
System.out.println("Dear " + fromto.from);
}
}
First of all, you should probably learn more about variable scope in Java. (Reading Sun's tutorials about Object-oriented Java-programming is probably a good idea)
The problem here is that the variable fromto is declared in a constructor and thus is only available from the scope of the constructor. Instead, get rid of that constructor (unless you really want to keep it, in which case you should make sure to initialize your from and to variables properly) and move the variable to your main function.
public class Letter {
private String from; // Sets from instance variable to be stored
private String to; /// Sets to instance vaariable to be stored
public Letter(String from, String to) {
this.from = from;
this.to = to;
}
public static void main(String[] args) {
Letter fromto = new Letter("Dylan", "April");
System.out.println("Dear " + fromto.from);
}
}
You need to first create a new instance of your Letter class before you can invoke fields and getter/setter-methods on that instance/object.
public static void main(String[] args)
{
Letter myLetter = new Letter();
System.out.println(myLetter.from);
}
Note the call on your private field from only succeeds as main is defined in the same class and therefore the created myLetter provides access to the field.
In practice you would define public setters and getters to access the private field.
You need to instantiate your Letter in the right scope. If you if you only need it inside the main method, the best place to create your instance is right at the beginning of the method block:
public class Letter {
private String from; // Sets from instance variable to be stored
private String to; /// Sets to instance vaariable to be stored
public Letter(String from, String to) {
this.from = from;
this.to = to;
}
public Letter() {
}
public static void main(String[] args) {
Letter fromto = new Letter("Dylan", "April");
System.out.println("Dear " + fromto.from);
}
}
About the no-args constructor, it is a good practice to declare one if the instance variables from and to are optional, so that you can also instantiate letter with the syntax new Letter(). If you do not declare any constructors, the compiler provides a empty constructor by default.
Actually, whenever you can, it is a good thing to follow JavaBeans conventions. Quoting Wikipedia:
The class must have a public default constructor (no-argument). This
allows easy instantiation within editing and activation frameworks.
The class properties must be accessible using get, set, is (used for
boolean properties instead of get) and other methods (so-called
accessor methods and mutator methods), following a standard naming
convention. This allows easy automated inspection and updating of bean
state within frameworks, many of which include custom editors for
various types of properties. Setters must receive only one argument.
The class should be serializable. It allows applications and
frameworks to reliably save, store, and restore the bean's state in a
fashion independent of the VM and of the platform.
Remove
public Letter(){
Letter fromto= new Letter("Dylan", "April");
}
then:
public static void main(String[] args){
Letter fromto= new Letter("Dylan", "April");
System.out.println("Dear " + fromto.from);
}