My program has 6 classes so I'm going to try and only post the methods involved with the issue I'm having. I'm trying to add donation objects that get their attributes from reading information from a file. My program wasn't printing out any of the donationList related information so I did a System.out.println(donationList.size()); and it's telling me that there are 0 objects in the list. I've been looking at this for a while and can't figure out where in the process the donation object is failing to be created correctly or added to the arraylist correctly.
This is where I call the method that starts the process.
public static void main(String[] args) {
readAndProcess();
This is the method that starts the process.
public static void readAndProcess() {
final String INPUT_FILENAME = "input/assn2input.txt";
File dataFile = new File(INPUT_FILENAME);
Scanner fileScanner = null;
try {
fileScanner = new Scanner(dataFile);
}catch (FileNotFoundException e) {
System.out.println("File not found exception for file " + e);
System.exit(0);
}
String oneLine;
String [] lineValues;
while(fileScanner.hasNextLine()) {
oneLine = fileScanner.nextLine();
lineValues = oneLine.split(",");
if(lineValues[0].equals("DONOR")) {
if (lineValues[1].equals("ADD") ) {
addDonor(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
else if ( lineValues[0].equals("Donation")) {
if (lineValues[1].equals("ADD")) {
addDonation(lineValues);
}
else if (lineValues[1].equals("DEL")) {
// call method to delete
}
}
}
}
This is the addDonation method which happens after the readAndProcess method.
public static void addDonation(String [] lineValues) {
Donation donation = new Donation();
setDonationAttributes(donation, lineValues);
if (donorImpl.isIDUnique(donation.getDonorID()) == false &&
donationImpl.isIDUnique(donation.getDonationID()) == true) {
donationImpl.add(donation);
}
else {
System.out.println("ERROR: The Donation either had a non-unique"
+ " donation ID or a unique Donor ID. Was not "
+ "added to list." + donation.toString());
}
}
This is the method that sets the donation object's attributes.
public static Donation setDonationAttributes (Donation donation,
String [] lineValues) {
donation.setDonationID(Integer.parseInt(lineValues[2]));
donation.setDonorID(Integer.parseInt(lineValues[3]));
donation.setDonationDescription(lineValues[4]);
if (donation.checkDescriptionLength() == false) {
System.out.println("ERROR: Donation description is longer "
+ "than 25 characters");
}
donation.setDonationAmount(Double.parseDouble(lineValues[5]));
donation.setDonationDate(lineValues[6]);
if (lineValues[7].equalsIgnoreCase("Y") ) {
donation.setTaxDeductible(true);
}
else {
donation.setTaxDeductible(false);
}
donation.setCheckNumber(Integer.parseInt(lineValues[8]));
if (donation.checkNumberCheck()== false) {
System.out.println("ERROR: Invalid check number is not between 100 "
+ "and 5000: " + lineValues[8]);
}
return donation;
}
This is the method that checks for unique ID for donationID.
public boolean isIDUnique(int donationID) {
int index;
for (index = 0; index < donationList.size(); ++index) {
if (donationID == donationList.get(index).getDonationID() ) {
return false;
}
}
return true;
}
This is the method for checking unique donorID.
public boolean isIDUnique(int donorID) {
int index;
for (index = 0; index < donorList.size(); ++index) {
if (donorID == donorList.get(index).getDonorID() ) {
return false;
}
}
return true;
}
This is the method in the DonationImpl class that adds the object to the arraylist. The instructions for this method told me to set it up as a boolean for whatever reason, I'm not exactly sure why.
public boolean add (Donation donation) {
if (donationList.add(donation)) {
return true;
}
return false;
}
The donationImpl class to show what the arrayList creation looks like.
public class DonationImpl {
// Data Field
private ArrayList<Donation> donationList = new ArrayList<Donation>();
//Getter
public ArrayList<Donation> getDonationList() {return donationList;}
The 1 and 3 in the following examples refer to a donorID. My donorID methods and creation are all working correctly.
Example lines of text:
DONATION,ADD,101,1,Payroll deduction,22.22,07/04/1776,Y,1001
DONATION,ADD,303,3,Anniversary contribution,111.00,07/04/1777,N,2244
You have a typo
else if ( lineValues[0].equals("Donation")) {
should be
else if ( lineValues[0].equals("DONATION")) {
Related
When the code is run, and I enter the credentials incorrectly, the successfully added message appears along with the error message and I am not sure why this is happening. We need to show an error message and a success message for our work.
When the code is run, and I enter the credentials incorrectly, the successfully added message appears along with the error message and I am not sure why this is happening. We need to show an error message and a success message for our work.
public class FXMLDocumentController implements Initializable {
private FadeTransition fade = new FadeTransition(
Duration.millis(5000)
);
Employee em = new Employee();
#Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
TV_id.setCellValueFactory(new PropertyValueFactory<>("ID"));
TV_fname.setCellValueFactory(new PropertyValueFactory<>("FirstName"));
TV_lname.setCellValueFactory(new PropertyValueFactory<>("LastName"));
TV_date.setCellValueFactory(new PropertyValueFactory<>("HireDate"));
fade.setNode(label_success);
fade.setFromValue(1.0);
fade.setToValue(0.0);
fade.setCycleCount(1);
fade.setAutoReverse(false);
}
#FXML
private void handleButtonAddAction(ActionEvent event) {
label_fail.setText("");
label_success.setText("Successfully Added");
int ID = 0, year = 0, month = 0, day = 0;
String fname = "", lname = "";
if (intValidation(TF_id) == true) {
label_id.setTextFill(Color.web("#000000"));
rec_id.setVisible(false);
ID = Integer.parseInt(TF_id.getText());
} else {
rec_id.setVisible(true);
label_id.setTextFill(Color.web("#ff0000"));
}
if (stringValidation(TF_fname) == true) {
label_fname.setTextFill(Color.web("#000000"));
rec_fname.setVisible(false);
fname = TF_fname.getText();
} else {
rec_fname.setVisible(true);
label_fname.setTextFill(Color.web("#ff0000"));
}
if (stringValidation(TF_lname) == true) {
label_fname.setTextFill(Color.web("#000000"));
rec_lname.setVisible(false);
lname = TF_lname.getText();
} else {
rec_lname.setVisible(true);
label_lname.setTextFill(Color.web("#ff0000"));
}
if (intValidation(TF_month) == true) {
label_date.setTextFill(Color.web("#000000"));
rec_month.setVisible(false);
month = Integer.parseInt(TF_month.getText());
} else {
rec_month.setVisible(true);
label_date.setTextFill(Color.web("#ff0000"));
}
if (intValidation(TF_day) == true) {
label_date.setTextFill(Color.web("#000000"));
rec_day.setVisible(false);
day = Integer.parseInt(TF_day.getText());
} else {
rec_day.setVisible(true);
label_date.setTextFill(Color.web("#ff0000"));
}
if (intValidation(TF_year) == true) {
label_date.setTextFill(Color.web("#000000"));
rec_year.setVisible(false);
year = Integer.parseInt(TF_year.getText());
} else {
rec_year.setVisible(true);
label_date.setTextFill(Color.web("#ff0000"));
}
if (!rec_id.isVisible() && !rec_fname.isVisible()
&& !rec_lname.isVisible() && !rec_month.isVisible()
&& !rec_day.isVisible() && !rec_year.isVisible()) {
if (em.addEmployee(fname, lname, ID, year, month, day) == false) {
label_fail.setText("No two employees can have the same ID.");
} else {
updateList();
label_success.setVisible(true);
fade.playFromStart();
TF_id.setText("");
TF_fname.setText("");
TF_lname.setText("");
TF_month.setText("");
TF_day.setText("");
TF_year.setText("");
}
}
}
private void updateList() {
TV_employee.getItems().clear();
}
private boolean intValidation(TextField txt) {
if (txt.getText().isEmpty() || txt.getText() == null) {
label_fail.setText("Error: You can not leave any fields blank.");
return false;
}
try {
int x = Integer.parseInt(txt.getText());
return true;
} catch (NumberFormatException e) {
label_fail.setText("Error: " + txt.getText() + " is not an integer.");
return false;
}
}
private boolean stringValidation(TextField txt) {
if (txt.getText().isEmpty() || txt.getText() == null) {
label_fail.setText("Error: You can not leave any fields blank.");
return false;
} else if (txt.getText().matches(".*\\d.*")) {
String invalidCharacters = txt.getText().replaceAll("[^0-9]", "");
label_fail.setText("Error: You've entered illegal characters in a text field. "
+ "Please remove \"" + invalidCharacters + "\" "
+ "from the highlighted field or enter a different value.");
return false;
} else {
return true;
}
}
}
What I expect is happening: The label_success is always visible. At the start it has no text so you won't see that it is visible, but this changes when you add the text to the label at the beginning of the method. The fade is responsible for setting it's opacity to 0. But when you enter an invalid value the fade is never started, so it remains at it's starting value, which means it will be visible. You could solve this by moving the label_success.setText("Successfully Added"); inside the final if-statement just above where you start your fade.
Also you can probably make your life more easy by separating the validation of the input from the visal setting of the labels into different methods as a lot is going on right now inside the same method.
I try to serialize and deserialize an ArrayList with some Objects. The first time I run the program, everything works, but the next times it doesn't work:
public class Test {
private static final String FILE_NAME = "Objects.ser";
public static void main(String[] args) {
ArrayList<CustomObject> customObjects = getCustomObjects();
System.out.println("CustomObjects count: "+customObjects.size());
System.out.println("Adding 5 CustomObjects");
Random rand = new Random();
for(int i=0; i<5; i++){
CustomObject obj = new CustomObject();
obj.setIntValue(rand.nextInt());
customObjects.add(obj);
}
System.out.println("CustomObjects count: "+customObjects.size());
System.out.println("Save and load CustomObjects");
saveCustomObjects(customObjects);
customObjects = getCustomObjects();
System.out.println("CustomObjects count: "+customObjects.size());
}
public static ArrayList<CustomObject> getCustomObjects(){
try (
FileInputStream fin = new FileInputStream(FILE_NAME);
ObjectInputStream ois = new ObjectInputStream(fin);
){
return (ArrayList<CustomObject>) ois.readObject();
} catch (Exception ex) {
return new ArrayList<>();
}
}
public static void saveCustomObjects(ArrayList<CustomObject> strategies) {
try(
FileOutputStream fout = new FileOutputStream(FILE_NAME, true);
ObjectOutputStream oos = new ObjectOutputStream(fout);
){
oos.writeObject(strategies);
//tried also with oos.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public class CustomObject implements Serializable{
static final long serialVersionUID = 42L;
private int intValue=0;
private EnumTypes enumType=EnumTypes.ENUM_TYPE_ONE;
public enum EnumTypes{
ENUM_TYPE_ONE, ENUM_TYPE_TWO
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public EnumTypes getEnumTypes() {
return enumType;
}
public void setEnumTypes(EnumTypes enumTypes) {
this.enumType = enumTypes;
}
#Override
public int hashCode() {
int hash = 3;
hash = 97 * hash + this.intValue;
hash = 97 * hash + Objects.hashCode(this.enumType);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final CustomObject other = (CustomObject) obj;
if (this.intValue != other.intValue) {
return false;
}
if (this.enumType != other.enumType) {
return false;
}
return true;
}
#Override
public String toString() {
return "CustomObject{" + "intValue=" + intValue + ", enumTypes=" + enumType + '}';
}
}
The output of the first run of the app shows everything like expected:
CustomObjects count: 0
Adding 5 CustomObjects
CustomObjects count: 5
Save and load CustomObjects
CustomObjects count: 5
But after the next runs, the output looks always like the file with the objects in the serialized ArrayList could not be overwritten:
CustomObjects count: 5
Adding 5 CustomObjects
CustomObjects count: 10
Save and load CustomObjects
CustomObjects count: 5
I tested in netbeans and console on mac. Does anyone know what the problem is?
That's exactly that, nothing is overwritten, since you explicitely chose to append rather than overwrite when writing to the file:
new FileOutputStream(FILE_NAME, true);
So the first run reads nothing, and appends a list of 5 elements to the file. The second run reads the unique list and appends another list of 10 elements to the file. The third run reads the first list of in the file, and appends yet another list of 10 elements, etc.
Remove the second argument, or set it to false.
For example, I am getting the error here- this is just a snippet. I got the error 3 times in 3 different operators.
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
I also have the same error here:
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
And then in my second class (the user interface portion), I keep getting this error: Exception in thread "main" java.lang.NoClassDefFoundError: Directory
Here is the entire code for that class:
import java.io.*;
import java.util.*;
public class DirectoryWithObjectDesign {
public static void main(String[] args) throws IOException {
String directoryDataFile = "Directory.txt";
Directory d = new Directory(directoryDataFile);
Scanner stdin = new Scanner(System.in);
System.out.println("Directory Server is Ready!");
System.out.println("Format: command name");
System.out.println("Enter ^Z to end");
while (stdin.hasNext()) {
String command = stdin.next();
String name = stdin.next();
if (command.equalsIgnoreCase("find")) {
if (d.inDirectory(name))
System.out.println(name + " is in the directory");
else
System.out.println(name + " is NOT in the directory");
}
else if (command.equalsIgnoreCase("add")) {
if (d.add(name))
System.out.println(name + " added");
else
System.out.println(name + " cannot add! " + "no more space or already in directory");
}
else if (command.equalsIgnoreCase("delete")) {
if (d.delete(name))
System.out.println(name + " deleted");
else
System.out.println(name + " NOT in directory");
}
else {
System.out.println("bad command, try again");
}
}
}
}
And here is the code for my directory class:
import java.util.*;
import java.io.*;
public class Directory {
//public static void main(String[] args) {
final int maxDirectorySize = 1024;
String directory[] = new String[maxDirectorySize];
int directorySize = 0;
File directoryFile = null;
Scanner directoryDataIn = null;
public Directory(String directoryFileName) {
directoryFile = new File(directoryFileName);
try {
directoryDataIn = new Scanner(directoryFile);
}
catch (FileNotFoundException e) {
System.out.println("File is not found, exiting!" + directoryFileName);
System.exit(0);
}
while (directoryDataIn.hasNext()) {
directory[directorySize++] = directoryDataIn.nextLine();
}
}
public boolean inDirectory(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return true;
else
return false;
}
}
public boolean add(String name) {
if (directory.length == 1024)
return false;
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name))
return false;
else
directory[directorySize++] = name;
return true;
}
}
public boolean delete(String name) {
for (int i = 0; i < directory.length; i++) {
if (directory[i].equalsIgnoreCase(name)) {
directory[i] = null;
return true;
}
else
return false;
}
}
public void closeDirectory() {
directoryDataIn.close();
PrintStream directoryDataOut = null;
try {
directoryDataOut = new PrintStream(directoryFile);
}
catch (FileNotFoundException e) {
System.out.printf("File %s not found, exiting!", directoryFile);
System.exit(0);
}
String originalDirectory[] = {"Mike","Jim","Barry","Cristian","Vincent","Chengjun","susan","ng","serena"};
if (originalDirectory == directory)
System.exit(0);
else
for (int i = 0; i < directorySize; i++)
directoryDataOut.println(directory[i]);
directoryDataOut.close();
}
}
The point is that the compiler can't know if your for loop will be entered at all. Therefore you need a final return after the end of the for loop, too. In other words: any path that can possibly be taken within your method needs a final return statement. One easy way to achieve this ... is to have only one return statement; and put that on the last line of the method. This could look like:
Object getSomething() {
Object rv = null; // rv short for "returnValue"
for (int i=0; i < myArray.length; i++) {
if (whatever) {
rv = godKnowsWhat;
} else {
rv = IdontCare;
}
}
return rv;
}
In your second example, the indenting seems to indicate that you have a return in the else statement
directory[directorySize++] = name;
return true;
But when you look closer, you will realize that there are TWO statements after the else
else
directory[directorySize++] = name;
return true;
So this actually reads like
else
directory[directorySize++] = name;
return true;
Meaning: always put {braces} around all your blocks, even for (supposedly) one-liner then/else lines. That helps to avoid such mistakes, when a one-liner turns into a two-liner (or vice versa ;-)
The "NoClassDefFoundException" means: within the classpath that is specified to java ... there is no class Directory.class
To resolve that, you should study what the java classpath is about; and how to set it correctly.
My program stops after the first element gets into array. Could you help me? Here's the code:
sorry for that
i've made some changes now ArrayQueue is my class where all my methods are implemented
QueueElement is another class that holds the type of element..
i think the problem now is at the ArrayQueue class
import java.io.*;
import java.util.Scanner;
public class QueueTest
{ private static Scanner scan =new Scanner(System.in);
public static void main(String[] args)
{
ArrayQueue queue = new ArrayQueue();
System.out.println("insert :" +
" P: to print the array "+
"S: to sort "+
"E: to empty");
do
{
if (userInput.startsWith("Y")) {
System.out.println("insert the value of element");
int vl = scan.nextInt();
System.out.println("insert the description");
String p = scan.next();
System.out.println("insert true or false");
boolean vlf = scan.nextBoolean();
queue.shtoElement(new QueueElement(vl, p, vlf));
} else if (userInput.startsWith("P")) {
queue.shfaqArray();//display the array
} else if (userInput.startsWith("S")) {
queue.rendit();//sort the array
} else if (userInput.startsWith("E")) {
queue.Empty();//empty array
}
System.out.println("Insert:" + " P: to display the array "
+ " S: to sort array "
+ " E: to empty");
userInput = scan.next();
} while (!userInput.equalsIgnoreCase("exit"));
}
}
here is the class ArrayQueue
public class ArrayQueue implements Queue
{
//build the queue
QueueElement[] tabela= new QueueElement[MADHESIA];
QueueElement element= new QueueElement();
//test if queue is empty
public boolean isEmpty()
{
boolean empty = true;
for(int k =0;k<tabela.length;k++)
{
if(tabela[k] !=null)
empty =false;
break;
}
return empty;
}
public boolean isFull()
{
boolean full=false;
for(int k=0;k<tabela.length;k++)
{
if(tabela[k]!=null)
full=true;
break;
}
return full;
}
//sort the array
public void rendit()
{
QueueElement temp=tabela[0];
for(int i=0;i<tabela.length;i++)
{
for(int j=i+1;j<tabela.length;j++)
if(tabela[j]!=null)
{
if(tabela[j].compareTo(tabela[i])==1)
{
tabela[j]=temp;
tabela[i]=tabela[j];
temp=tabela[i];
}
else
{
nrElementeve++;
}
}
if(tabela[i].getVlefshmeria()==false)
{
hiqElement(i,temp);
}
}
}
// add element into the array
public void shtoElement(QueueElement el)
{
if(isEmpty())
{
tabela[0]=el;
}
else
{
for(int i=0;i<tabela.length;i++)
{
if(tabela[i]!= null && (el.compareTo(tabela[i])==0))
{
System.out.println("element can't be added into array cause it exists !");
}
{
if(isFull())
{
int index=tabela.length;
tabela=rritMadhesine(tabela);
tabela[index]=el;
}
else
{
for(int j=0;j<tabela.length;j++)
{
if(tabela[j]==null)
tabela[j]=el;
break;
}
}
}
}
}
}
//find max of array
public QueueElement gjejMax()
{
QueueElement max = tabela[0];
for (QueueElement element :tabela)
{
if(element.getValue() > max.getValue())
{
max =element;
}
return max;
}
return max;
}
//find min of array
public QueueElement gjejMin()
{
QueueElement min= tabela[0];
for(QueueElement element : tabela)
{
if(element.getValue()< min.getValue())
{
min=element;
}
return min;
}
return min;
}
//remove element from array
public void hiqElement(int indeksi, QueueElement temp)
{
if(tabela.length > 0)
{
if(gjejMax().compareTo(temp)==0 || gjejMin().compareTo(temp)==0)
{
System.out.println("element can't be removed!");
}
else
{
for(int i=indeksi;i<tabela.length;i++)
{
tabela[i]=tabela[i+1];
}
}
nrElementeve--;
}
}
//empty array
public void Empty()
{
tabela= new QueueElement[MADHESIA];
}
//display the array
public void shfaqArray()
{
for(int i=0;i< tabela.length;i++)
{
if(tabela[i]!=null)
{
System.out.println(tabela[i]);
}
else
break;
}
}
//increase the length of array
public static QueueElement [] rritMadhesine(QueueElement[] array){
QueueElement[] tab=new QueueElement[array.length+2];
return tab;
}
private int nrElementeve;
private static final int MADHESIA = 10;
}
Don't know what ArrayQueue and QueueElement are, but...
It seems like you're reading user input then going through a decision tree to decide what to do based on that input. But at each point, you are re-reading the user input:
if(scan.next().startsWith("Y"))
{
System.out.println("Jepni vleren e elem");
vl=scan.nextInt();
System.out.println("Jepni pershkrimin e elem");
p=scan.next();
System.out.println("Jepni vlefshmerine e elem");
vlf=scan.nextBoolean();
queue.shtoElement(new QueueElement(vl,p,vlf));
}
else
{
if(scan.next().startsWith("P"))
queue.shfaqArray();
}
if(scan.next().startsWith("E"))
queue.Empty();
if(scan.next().startsWith("S"))
queue.rendit();
else
{
break;
}
I think you want something more like:
String userInput = scan.next();
if(userInput.startsWith("Y"))
{
System.out.println("Jepni vleren e elem");
vl=scan.nextInt();
System.out.println("Jepni pershkrimin e elem");
p=scan.next();
System.out.println("Jepni vlefshmerine e elem");
vlf=scan.nextBoolean();
queue.shtoElement(new QueueElement(vl,p,vlf));
}
else if(userInput.startsWith("P"))
queue.shfaqArray();
else if(userInput.startsWith("E"))
queue.Empty();
else if(userInput.startsWith("S"))
queue.rendit();
else
{
break;
}
Where you read the user input once (String userInput = scan.next();) and then decide what to do based on the userInput variable and not re-scan each time. Also, it looks like you might be missing a couple of else statements somewhere in the middle there.
So I am supposed to make 3 classes and am given a 4th class to use for a user interface. One class (DBBinding) is supposed to have a String key and String value and take something like name:Alien or star: harry dean and make name or star be the "key" and the other is the "value" the next class (DBrecord) is to hold a group of these "bindings" as one record. I have chosen to keep a group of these bindings in a ArrayList. The third class(DBTable) is another ArrayList but of . I am at the point where I am reading in a line of txt from file where each line of txt is going to be one DBrecord that we know will be in correct formatting(key:value, key:value, key:value, and so on).
Where I am having trouble is within the DBrecord class. I have a method(private void addBindingToRecord(String key_, String value_)) that is called from (public static DBrecord createDBrecord(String record)) from within the DBrecord class here are each methods code.
I am having trouble with the addBindingToRecord method ... it null pointer exceptions on the first time used. I think it has to do with sytax and how I am calling the "this.myDBrecord.add(myDBBinding);"... have tried it multiple ways with same result....
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
myRecord.addBindingToRecord(temp2[0], temp2[1]);
}
}
return myRecord;
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);///Here is where my null pointer exception is.
}
I am going to post the full code of all my classes here so you have it if need to look at. Thank for any help, hints, ideas.
package DataBase;
import java.io.*;
public class CommandLineInterface {
public static void main(String[] args) {
DBTable db = new DBTable(); // DBTable to use for everything
try {
// Create reader for typed input on console
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String line;
while (true) {
int length = 0;
int selectedLength = 0;
// YOUR CODE HERE
System.out.println("\n" + length + " records (" + selectedLength + " selected)");
System.out.println("r read, p print, sa select and, so select or, da ds du delete, c clear sel");
System.out.print("db:");
line = reader.readLine().toLowerCase();
if (line.equals("r")) {
System.out.println("read");
String fname;
System.out.print("Filename:");
//fname = reader.readLine();////ADD BACK IN AFTER READ DEBUGED
// YOUR CODE HERE
fname="movie.txt";
db.readFromFile(fname);
}
else if (line.equals("p")) {
System.out.println("print");
// YOUR CODE HERE
DBTable.print();
}
else if (line.equals("da")) {
System.out.println("delete all");
// YOUR CODE HERE
}
else if (line.equals("ds")) {
System.out.println("delete selected");
// YOUR CODE HERE
}
else if (line.equals("du")) {
System.out.println("delete unselected");
// YOUR CODE HERE
}
else if (line.equals("c")) {
System.out.println("clear selection");
/// YOUR CODE HERE
}
else if (line.equals("so") || line.equals("sa")) {
if (line.equals("so")) System.out.println("select or");
else System.out.println("select and");
System.out.print("Criteria record:");
String text = reader.readLine(); // get text line from user
// YOUR CODE HERE
}
else if (line.equals("q") || line.equals("quit")) {
System.out.println("quit");
break;
}
else {
System.out.println("sorry, don't know that command");
}
}
}
catch (IOException e) {
System.err.println(e);
}
}
}
package DataBase;
import java.util.*;
import java.io.*;
public class DBTable {
static ArrayList<DBrecord> myDBTable;
public DBTable()
{
ArrayList<DBrecord> myDBTable= new ArrayList<DBrecord>();
}
public static void addRecordToTable(DBrecord myRecord)//added static when added addRecordToTable in readFromFile
{
if(myRecord!=null)
{myDBTable.add(myRecord);}
}
public static void readFromFile(String FileName)
{
try
{
FileReader myFileReader=new FileReader(FileName);
String line="Start";
BufferedReader myBufferdReader=new BufferedReader(myFileReader);
while(line!="\0")
{
line=myBufferdReader.readLine();
if(line!="\0")
{
System.out.println(line);//TEST CODE
addRecordToTable(DBrecord.createDBrecord(line));// made addRecordToTable static.
}
}
}catch(IOException e)
{System.out.println("File Not Found");}
}
public static void print()
{
if (myDBTable==null)
{
System.out.println("EMPTY TABLE");
return;
}
else
{
for (int i=0; i<myDBTable.size(); i++)
{
System.out.println(myDBTable.get(i).toString());
}
}
}
}
package DataBase;
import java.util.*;
import java.lang.reflect.Array;
//import DataBase.*;//did not help ... ?
public class DBrecord {
boolean select;
String key;
//need some type of collection to keep bindings.
ArrayList<DBBinding> myDBrecord;
public DBrecord()
{
//DBrecord myRecord=new DBrecord();
select=false;
ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
}
private void addBindingToRecord(String key_, String value_)
{
DBBinding myDBBinding=new DBBinding(key_, value_);
//System.out.println(myDBBinding.toString());//for testing
if(myDBBinding!=null)//////////////ADDED
this.myDBrecord.add(myDBBinding);
System.out.println(key_);//for testing
System.out.println(value_);//for testing
}
public String toString()
{
//out put key first then all values in collection/group/record. use correct formatting.
StringBuilder myStringbuilder=new StringBuilder();
for (int i=0;i<this.myDBrecord.size();i++)
{
myStringbuilder.append(myDBrecord.get(i).toString());
myStringbuilder.append(", ");
}
myStringbuilder.delete(myStringbuilder.length()-2, myStringbuilder.length()-1);//delete last ", " thats extra
return myStringbuilder.toString();
}
public static DBrecord createDBrecord(String record)//takes a string and breaks it into DBBindings and makes a record with it.
{
//System.out.println("HERE");//for testing
DBrecord myRecord=new DBrecord();
String temp[];
temp=record.split(",",0);
if(temp!=null)
{
//System.out.println("HERE");//for testing
//for(int i=0; i<Array.getLength(temp); i++) ///for testing
//{System.out.println(temp[i]);}
for(int i=0; i<Array.getLength(temp); i++)
{
System.out.println("HERE");//for testing
String temp2[];
temp2=temp[i].split(":",0);
System.out.println(temp2[0]);//for testing
System.out.println(temp2[1]);//for testing
myRecord.addBindingToRecord(temp2[0], temp2[1]);
System.out.println(temp2[0]+ " "+ temp2[1]);////test code
}
}
return myRecord;
}
}
package DataBase;
public class DBBinding {
private String key;
private String value;
public DBBinding(String key_, String value_)
{
key =key_;
value=value_;
}
public String getKey()
{return key;}
public String getValue()
{return value;}
public String toString()
{return key+": "+value;}
}
In your constructor: ArrayList<DBBinding> myDbrecord=new ArrayList<DBBinding>();
You only create a local variable named myDbrecord and initialize it, instead of initializing the field myDBrecord.
You probably wanted instead:
myDBrecord = new ArrayList<DBBinding>();