Reputation: 49
Can anyone tell me why the array size of the titles array in the data definition class doesn't equal the value the user inputted that was passed in from the implementation class and set as an instance variable in the data definition class?
This is the Data Definition Class.
public class Photograph {
private int maxTakes;
public Photograph() {
this.titles = new String[this.maxTakes];
numPhotosTaken = 0;
}
public void setMaxTakes(int maxTakes) {
this.maxTakes = maxTakes;
}
public boolean setTitle(String title) {
if (this.numPhotosTaken < this.titles.length) {
this.titles[numPhotosTaken] = title;
numPhotosTaken++;
return true;
}
else {
return false;
}
}
}
This is the implementation class.
import javax.swing.JOptionPane;
public class MakePhotographs {
public static void main (String[] args) {
Photograph photo;
do {
photo = create();
} while (JOptionPane.showConfirmDialog(null, "Enter another couple?") == JOptionPane.YES_OPTION);
}
private static Photograph create() {
Photograph photo = new Photograph();
photo.setMaxTakes(Integer.parseInt(JOptionPane.showInputDialog("Enter maximum number of photos to take")));
do {
String title = JOptionPane.showInputDialog("Enter title of photo");
if (!photo.setTitle(title)) {
JOptionPane.showMessageDialog(null, "No more photos allowed!");
}
} while (JOptionPane.showConfirmDialog(null, "Enter another photo?") == JOptionPane.YES_OPTION);
return photo;
}
}
Upvotes: 0
Views: 84
Reputation: 2239
Your array is created before you can call setMaxTakes()
. After you have already created your array with the length of maxTakes
, changing the value of maxTakes
does not accomplish anything.
You need to either change the method of setMaxTakes()
to the following:
public void setMaxTakes(int maxTakes) {
titles = new String[maxTakes];
}
or go with the answer posted by @Gremash here (which is the proper way to do it).
Upvotes: 1
Reputation: 8308
Create a constructor that takes in the maxTakes value and use that:
Photograph photo = new Photograph(Integer.parseInt(JOptionPane.showInputDialog("Enter maximum number of photos to take")));
You don't need the setMaxTakes
anymore since it's been set within the constructor.
class Photograph {
private int maxTakes;
private String[] titles;
private int numPhotosTaken;
public Photograph(int maxTakes) {
this.maxTakes = maxTakes;
this.titles = new String[maxTakes];
numPhotosTaken = 0;
}
public boolean setTitle(String title) {
if (this.numPhotosTaken < this.titles.length) {
this.titles[numPhotosTaken] = title;
numPhotosTaken++;
return true;
}
else {
return false;
}
}
}
Upvotes: 2