The following code should read a list of students and their grades from a file, compare them to each other then display the student with the highest average
public class CSDept implements Comparable{
private String studentName;
private double java;
private double dataStructure;
private double algorithms;
private int numStudents;
public CSDept(){
}
public CSDept(String studentName,double java,double dataStructure,double algorithms){
this.studentName=studentName;
this.java=java;
this.dataStructure=dataStructure;
this.algorithms=algorithms;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getJava() {
return java+" ";
}
public void setJava(double java) {
this.java = java;
}
public String getDataStructure() {
return dataStructure+" ";
}
public void setDataStructure(double dataStructure) {
this.dataStructure = dataStructure;
}
public String getAlgorithms() {
return algorithms+" ";
}
public void setAlgorithms(double algorithms) {
this.algorithms = algorithms;
}
public int getNumStudents() {
return numStudents;
}
public double getAvg(){
return (java+algorithms+dataStructure)/3;
}
public int compareTo(Object student) {
if(this.getAvg()>((CSDept)student).getAvg()) return 1;
if (this.getAvg()<((CSDept)student).getAvg()) return -1;
return 0;
}
public String toString(){
return studentName+":\n"+"\t"+"Java: "+java+"\t"+"Data Structure : "+dataStructure+"\t"+"Algorithms: "+algorithms+"\n";
}}
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.TitledBorder;
public class CSDeptFrame extends JFrame{
private JPanel pnlInput=new JPanel(new GridLayout(4,2));
private JPanel pnlOutput=new JPanel(new BorderLayout());
private JPanel pnlFinal=new JPanel(new GridLayout(1,2));
private TitledBorder brdInput=new TitledBorder("Marks");
private TitledBorder brdOutput=new TitledBorder("First Student");
private JLabel lblName=new JLabel("Student Name");
private JLabel lblJava=new JLabel("Java");
private JLabel lblDataStructure=new JLabel("Data Structure");
private JLabel lblAlgorithm=new JLabel("Algorithm");
static JLabel lblFirst=new JLabel("The First Student is :");
static JTextField txtName=new JTextField(20);
static JTextField txtJava=new JTextField(20);
static JTextField txtDataStructure=new JTextField(20);
static JTextField txtAlgorithm=new JTextField(20);
static JButton btnFirst=new JButton("Who is The First Student?");
public CSDeptFrame(String title){
super(title);
pnlInput.setBorder(brdInput);
pnlInput.add(lblName);
pnlInput.add(txtName);
pnlInput.add(lblJava);
pnlInput.add(txtJava);
pnlInput.add(lblDataStructure);
pnlInput.add(txtDataStructure);
pnlInput.add(lblAlgorithm);
pnlInput.add(txtAlgorithm);
pnlOutput.setBorder(brdOutput);
pnlOutput.add(btnFirst,BorderLayout.NORTH);
pnlOutput.add(lblFirst,BorderLayout.SOUTH);
pnlFinal.add(pnlInput);
pnlFinal.add(pnlOutput);
setLayout(new BorderLayout());
add(pnlFinal);}
public static void main(String[] args){
CSDeptFrame frame=new CSDeptFrame("CS DEPT");
frame.setSize(450,200);
frame.setResizable(false);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
final ArrayList<CSDept> cS= new ArrayList();
File readFile =new File("read.txt");
final File writeFile=new File("write.txt");
try {
Scanner scan=new Scanner(readFile);
while(scan.hasNext()){
CSDept student=new CSDept();
student.setStudentName(scan.next());
student.setJava(scan.nextDouble());
student.setDataStructure(scan.nextDouble());
student.setAlgorithms(scan.nextDouble());
cS.add(student);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "OPS! File is not found");
}
btnFirst.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
CSDept firstStudent=new CSDept();
firstStudent.setStudentName(cS.get(0).getStudentName());
firstStudent.setJava(Double.parseDouble(cS.get(0).getJava()));
firstStudent.setDataStructure(Double.parseDouble(cS.get(0).getDataStructure()));
firstStudent.setAlgorithms(Double.parseDouble(cS.get(0).getAlgorithms()));
for (int i=0;i<cS.size();i++){
if (cS.get(i).compareTo(cS.get(i+1))==-1){
firstStudent=cS.get(i+1);
}
}
txtName.setText(firstStudent.getStudentName());
txtJava.setText(firstStudent.getJava());
txtDataStructure.setText(firstStudent.getDataStructure());
txtAlgorithm.setText(firstStudent.getAlgorithms());
lblFirst.setText("The First Student is: "+ txtName.getText());
PrintWriter out;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter(writeFile,true)));
for (CSDept cs: cS){
out.println(cs.toString());
out.print("The first student is " + firstStudent.toString());
}
out.close();
} catch (IOException e1) {
e1.printStackTrace();
JOptionPane.showMessageDialog(null, "OPS! File in Not Found");
}
}
});
}}
But the problem is that the following statements don't add any objects to the arraylist, what's the problem with it?
try {
Scanner scan=new Scanner(readFile);
while(scan.hasNext()){
CSDept student=new CSDept();
student.setStudentName(scan.next());
student.setJava(scan.nextDouble());
student.setDataStructure(scan.nextDouble());
student.setAlgorithms(scan.nextDouble());
cS.add(student);
}
You problem is that you are trying to get an element at a specific index from an empty list:
final ArrayList<CSDept> cS= new ArrayList();
// ...
public void actionPerformed(ActionEvent e) {
// ...
firstStudent.setStudentName(cS.get(0).getStudentName()); // ArrayList cS is empty here
// ...
Maybe you could add a check to make sure the list is not empty before accessing the elements:
public void actionPerformed(ActionEvent e) {
if(!cS.isEmpty()) {
// do stuff
}
The reason your list is empty could be that you are reading an empty file "read.txt" so your while loop condition is never true
Scanner scan=new Scanner(readFile); // this text file is probably empty
while(scan.hasNext()){ // which makes this condition always false so loop is never executed
CSDept student=new CSDept();
student.setStudentName(scan.next());
student.setJava(scan.nextDouble());
student.setDataStructure(scan.nextDouble());
student.setAlgorithms(scan.nextDouble());
cS.add(student);
}
Furthermore, you have an ArrayIndexOutOfBoundsException risk in the for loop inside actionPerformed(). You compare current element with the next element which will, once i corresponds to the index of the last element, give an AIOBE in the comparison statement with element at index i + 1:
for (int i=0;i<cS.size();i++){
if (cS.get(i).compareTo(cS.get(i+1))==-1){ // once i = cS.size() - 1, you will get an AIOBE here
firstStudent=cS.get(i+1);
}
}
You can fix this by starting the loop at i = 1 and comparing with element at i - 1 or use a forEach loop which is a cleaner way of achieving this since it doesn't involve indexed access.
Related
I'm currently working on a project for a class I have, where we have to create a GUI that asks for a number, then read a binary files of 10,000 customers and return the other information on the one with the customer number entered. We also have to have an error that pops up as a JOptionPane when a number outside of 1-10,000 is entered. I'm having some problems with the error message, and my professor also said we need to have a method with this signature:
private Customer getCustomer(long custNumber) throws IOException
that searches the file and returns a customer object. I'm also not sure where exactly to do that. So I started with what I already know, and here's what I have:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class CustomerLocator extends JFrame
{
private JPanel panel;
private JLabel custNumLabel;
private JLabel custNameLabel;
private JLabel custDisLabel;
private JLabel custBalLabel;
private JLabel custPrefLabel;
private JTextField custNumField;
private JTextField custNameField;
private JTextField custDisField;
private JTextField custBalField;
private JTextField custPrefField;
private JButton findCustBut;
private final int WINDOW_WIDTH = 300;
private final int WINDOW_HEIGHT = 500;
public CustomerLocator()
{
setTitle("Customer Locator");
setSize(WINDOW_WIDTH, WINDOW_HEIGHT);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
buildPanel();
add(panel);
setVisible(true);
}
private void buildPanel()
{
custNumLabel = new JLabel("Enter a valid Customer Number: ");
custNumField = new JTextField(10);
custNameLabel = new JLabel("Customer Name: ");
custNameField = new JTextField(10);
custNameField.setEditable(false);
custDisLabel = new JLabel("Customer Discount: ");
custDisField = new JTextField(10);
custDisField.setEditable(false);
custBalLabel = new JLabel("Customer Balance: ");
custBalField = new JTextField(10);
custBalField.setEditable(false);
custPrefLabel = new JLabel("Preferred? ");
custPrefField = new JTextField(10);
custPrefField.setEditable(false);
findCustBut = new JButton("Find this Customer!");
panel = new JPanel();
findCustBut.addActionListener(new ListenerToFindCustomer());
panel.add(custNumLabel);
panel.add(custNumField);
panel.add(findCustBut);
panel.add(custNameLabel);
panel.add(custNameField);
panel.add(custDisLabel);
panel.add(custDisField);
panel.add(custBalLabel);
panel.add(custBalField);
panel.add(custPrefLabel);
panel.add(custPrefField);
}
private class ListenerToFindCustomer implements ActionListener
{
public void actionPerformed(ActionEvent e)
{
String numEnteredStr;
long custNumEntered;
String custName;
boolean preferred;
String preferredDisplay;
double acctBal;
String acctBalDisplay;
double discount;
String discountDisplay;
numEnteredStr = custNumField.getText();
custNumEntered = Long.parseLong(numEnteredStr);
int ct=0;
try
{
FileInputStream inStream =
new FileInputStream("c:\\cps\\CustomerObjects.dat");
// DataInputStream inputFile = new DataInputStream(inStream);
ObjectInputStream objectInputFile =
new ObjectInputStream(inStream);
while(true)
{
ct++;
Customer obj = (Customer)objectInputFile.readObject();
//System.out.println(obj.getCustName());
if (custNumEntered == obj.getCustNum())
{
custName = obj.getCustName();
acctBal = obj.getBalance();
acctBalDisplay = Double.toString(acctBal);
discount = obj.getDiscount();
discountDisplay = Double.toString(discount);
preferred = obj.getPreferred();
preferredDisplay = Boolean.toString(preferred);
custNameField.setText(custName);
custBalField.setText(acctBalDisplay);
custPrefField.setText(preferredDisplay);
custDisField.setText(discountDisplay);
if (custNameField == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
}
}
}
catch (Exception ex)
{
System.out.println(ex.toString());
}
}
}
public static void main(String[] args)
{
new CustomerLocator();
}
}
So, with this, the JOptionPane doesn't show up, so my questions are
1. How do I get the error message to pop up?
2. How do I incorporate the method my professor requested?
Your code
if (custNameField == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
should read
if (custName == null)
{
JOptionPane.showMessageDialog(null, "Error");
}
It should also be moved outside of the while loop.
You also need a way to break the loop once you reach the end of the file.
Everything inside and including your try { ... } catch (Exception ex) { ... } can be moved to the method that your instructor suggests.
You should also change the try-catch to have another catch (IOException ioEx) { throw ioEx; }
I am creating a program that resembles a student registration system. I am able to add as many students as I want and can find a student by searching for their ID number. But I am stuck on the code for removing and updating the students. Any Suggestions?
import java.io.Serializable;
import java.util.ArrayList;
public class School implements Serializable
{
ArrayList<Student>students;
/**
Creates an arrayList that holds student objects
*/
public School()
{
students = new ArrayList<Student>();
}
/**
Adds a student to the arrayList
*/
public void addStudent(Student a)
{
students.add(a);
}
public String toString()
{
String content = "";
if(!students.isEmpty())
{
for(int i = 0; i<students.size(); i++)
{
content = content + students.get(i).getID() + " " + students.get(i).getName() + " " + students.get(i).getMajor() + " " + students.get(i).getQPA() + "\n";
}
}
return content;
}
public void remove(Student a)
{
remove(a);
}
}
import java.io.Serializable;
/**
This class creates a persistent student object with set parameters.
*/
public class Student implements Serializable
{
private int studID;
private String name;
private String major;
private double QPA;
/**
Creates a student object with an id, name, major, and QPA
#param aNum as an int
#param aName as a String
#param aMajor as a String
#param aQPA as a double
*/
public Student(int aNum, String aName, String aMajor, double aQPA)
{
studID = aNum;
name = aName;
major = aMajor;
QPA = aQPA;
}
/**
Gets the student's id
#return studID as an int
*/
public int getID()
{
return studID;
}
/**
Gets the student's name
#return name as String
*/
public String getName()
{
return name;
}
/**
Gets the student's major
#return major as a String
*/
public String getMajor()
{
return major;
}
/**
Gets the student's QPA
#return QPA as a double
*/
public double getQPA()
{
return QPA;
}
}
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class GUI extends JFrame
{
private static final int FRAME_WIDTH = 700;
private static final int FRAME_HEIGHT = 500;
private JPanel panel;
private JButton add;
private JButton remove;
private JButton update;
private JButton clear;
private JLabel Name;
private JTextField nameField;
private JLabel Major;
private JTextField majorField;
private JLabel ID;
private JTextField idField;
private JLabel QPA;
private JTextField qpaField;
private JTextArea area;
private JButton find;
School firstSchoolOfJava = new School();
public GUI()
{
createButtons();
createLabel();
createTextField();
createPanel();
setSize(FRAME_WIDTH,FRAME_HEIGHT);
}
public void createButtons()
{
add = new JButton("Add");
update = new JButton("Update");
clear = new JButton("Clear");
remove= new JButton("Remove");
find = new JButton("Find");
class ButtonListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
Student newStudent = new Student(Integer.parseInt(idField.getText()), nameField.getText(), majorField.getText(), Double.parseDouble(qpaField.getText()));
firstSchoolOfJava.addStudent(newStudent);
System.out.println(firstSchoolOfJava.toString());
}
}
ButtonListener listener = new ButtonListener();
add.addActionListener(listener);
class ButtonListener1 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if(!firstSchoolOfJava.equals((idField.getText())))
{
}
}
}
ButtonListener1 listener1 = new ButtonListener1();
update.addActionListener(listener1);
class ButtonListener2 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
idField.setText(null);
nameField.setText(null);
majorField.setText(null);
qpaField.setText(null);
}
}
ButtonListener2 listener2 = new ButtonListener2();
clear.addActionListener(listener2);
class ButtonListener3 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if(!firstSchoolOfJava.equals(idField.getText()))
{
}
System.out.println(firstSchoolOfJava.toString());
}
}
ButtonListener3 listener3 = new ButtonListener3();
remove.addActionListener(listener3);
class ButtonListener4 implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
if(!firstSchoolOfJava.equals(idField.getText()))
{
System.out.println("You found the account: " + idField.getText() + nameField.getText() + majorField.getText() + qpaField.getText());
}
}
}
ButtonListener4 listener4 = new ButtonListener4();
find.addActionListener(listener4);
}
public void createLabel()
{
Name = new JLabel("Name");
Major = new JLabel("Major");
ID = new JLabel("Student ID");
QPA = new JLabel("QPA");
}
public void createTextField()
{
final int FIELD_WIDTH = 10;
nameField = new JTextField(FIELD_WIDTH);
majorField = new JTextField(FIELD_WIDTH);
idField = new JTextField(FIELD_WIDTH);
qpaField = new JTextField(FIELD_WIDTH);
area = new JTextArea();
}
public void createPanel()
{
panel = new JPanel();
panel.add(ID);
panel.add(idField);
panel.add(Name);
panel.add(nameField);
panel.add(Major);
panel.add(majorField);
panel.add(QPA);
panel.add(qpaField);
panel.add(add);
panel.add(remove);
panel.add(update);
panel.add(clear);
panel.add(find);
panel.add(area);
add(panel);
}
}
public void remove(Student a)
{
students.remove(a);
}
You should remove from students. you just have remove(a)
You can do this to get the student
public void actionPerformed (ActionEvent event)
{
if(!firstSchoolOfJava.equals(idField.getText()))
{
// input should first be parsed to an int (id type is an int)
int id = Integer.parseInt(idField.getText());
Student s;
for (int i = 0; i < firstChoolOfJava.getStudents().size(); i++){
// check to see if the ids match. If they do, remove that student
if ((firstChoolOfJava.getStudents().get(i).getID()) == id) {
s = firstChoolOfJava.getStudents().get(i);
firstSchoolOfJava.remove(s); // you're removing this student
break;
}
}
}
System.out.println(firstSchoolOfJava.toString());
}
For this code to work You need to have a getStudents accessor method in you School
public ArrayList<Student> getStudents(){
return students;
}
To update a student
public void actionPerformed (ActionEvent event)
{
String name = nameField.getText();
String major = majorField.getText();
double gpa = Double.parseDouble(gpaField.gtText());
int id = Integer.parseInt(idField.getText());
Student s = new Student(id, name, major, gpa); // or whatever your constructor looks like.
Student s1;
for (int i = 0; i < firstSchoolOfJava.getStudents().size(); i++){
s1 = firstSchoolOfJava.getStudents().get(i);
if (s1.getId() == id){
firstSchoolOfJava.getStudents().set(i, s);
break;
}
}
}
Note: The above code is considering all fields are filled in correctly. If you just want to update one field where others are empty, you need to do some check to see which fields are empty.
Your question needs to be more clear. Do you want to delete all of the students? Or would you like to delete a student based on an unique student ID? To get you started, here is some basic pseudo code:
public boolean removeStudent(int uniqueID)
{
for(loop thru students)
{
if(listOfStudents.get(i).getId() == uniqueID)
{
listOfStudents.remove(i);
updateView();
return true;
}
}
return false;
}
Also, when you add a student you do the following:
/*
* Adds a student to the arrayList
*/
public void addStudent(Student a)
{
students.add(a); <-- You call add() from the ArrayList of students.
}
However, when you remove a student you do the following:
public void remove(Student a)
{
remove(a); <-- You do not call the ArrayList's remove() method at all. Instead,
you call the local remove() method defined in your School class.
}
Instead do the following:
public void remove(Student a)
{
students.remove(a); <-- Call the ArrayList's remove() method instead.
}
Also, what do you mean by update the students? I assume that you mean updating a display or GUI based on the updated student list? Otherwise, I am confused because the ArrayList will 'update' itself whenever a student is added or removed.
public void updateStudent(Student student, double GPA, String major)
{
for(loop thru list of students)
{
if(listOfStudents.get(i).equals(student))
{
listOfStudents.get(i).setGPA(GPA);
listOfStudents.get(i).setMajor(major);
}
}
}
EDIT
I've made several corrections and am now able to compile. When attempting to add a contact to the file I receive a null pointer exception at line 13 of the ContactsCollection class:
for (int i = 0; i < contactList.size(); i++)
and line 93 of the Contacts (GUI) class:
contactList.add(contact);
Contacts class:
import java.util.*;
import java.io.*;
public class Contact implements Serializable
{
public static final long serialVersionUID = 42L;
public String name, number;
Contact()
{
name = "No name";
number = "No number";
}
Contact (String theName, String theNumber)
{
this.name = theName;
this.number = theNumber;
}
public void setName(String aName)
{
this.name = aName;
}
public void setNumber(String aNumber)
{
this.number =aNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String toString()
{
return name + ": " + number;
}
public boolean equals(Contact other)
{
if (name.equals(other.getName()) && number.equals(other.getNumber()))
{
return(true);
}
else
{
return(false);
}
}
}
Contacts Collection class
import java.io.*;
import java.util.*;
class ContactsCollection
{
public static ArrayList<Contact> contactList;
public static void write()
{
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("contactList.dat"));
for (int i = 0; i < contactList.size(); i++)
{
out.writeObject(contactList.get(i));
}
out.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void read()
{
contactList = new ArrayList<Contact>();
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("contactList.dat"));
Contact temp;
while (in.available()!=0)
{
temp = (Contact)in.readObject();
contactList.add(temp);
}
in.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Contacts (GUI) class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.Timer;
import java.util.*;
class Contacts extends JFrame implements ActionListener, WindowListener
{
public static final int WIDTH = 400;
public static final int HEIGHT = 600;
public static final int SMALL_WIDTH = 200;
public static final int SMALL_HEIGHT = 100;
private static final Dimension stdBtn = new Dimension(150, 50);
JPanel centerPanel, northPanel, southPanel;
ImageIcon icon;
JLabel picture;
JButton addContact, displayContacts;
JScrollPane scroll;
JTextArea textArea;
Clock clock;
Background background;
Contact contact;
ArrayList<Contact> contactList;
public Contacts()
{
super("Contacts");
this.setLayout(new BorderLayout());
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(this);
this.setLocationRelativeTo(null);
centerPanel = new JPanel();
northPanel = new JPanel();
southPanel = new JPanel();
centerPanel.setBackground(Color.BLACK);
southPanel.setBackground(Color.BLACK);
clock = new Clock();
northPanel.add(clock);
icon = new ImageIcon("ContactsBackground.jpg");
picture = new JLabel(icon);
centerPanel.add(picture);
textArea = new JTextArea("", 10, 30);
textArea.setEditable(false);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
centerPanel.add(scroll);
JButton displayContacts = new JButton("Display contacts");
displayContacts.addActionListener(this);
southPanel.add(displayContacts);
JButton addContact = new JButton("Add contact");
addContact.addActionListener(this);
southPanel.add(addContact);
this.add(northPanel, BorderLayout.NORTH);
this.add(centerPanel, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
contactList = new ArrayList<Contact>();
JButton source = (JButton)e.getSource();
String contactInput = source.getText();
if (contactInput == "Display contacts")
{
ContactsCollection.read();
for (int i = 0; i < contactList.size(); i++)
{
contact = (Contact)contactList.get(i);
textArea.setText(contact.getName() + "," + contact.getNumber() + "\n");
}
}
if (contactInput == "Add contact")
{
String name = JOptionPane.showInputDialog(null, "Enter Name");
String number = JOptionPane.showInputDialog(null, "Enter Number");
contact = new Contact(name, number);
contactList.add(contact);
ContactsCollection.write();
}
}
public void windowOpened(WindowEvent e)
{}
public void windowClosing(WindowEvent e)
{
this.setVisible(false);
background = new Background();
background.setVisible(true);
}
public void windowClosed(WindowEvent e)
{}
public void windowIconified(WindowEvent e)
{}
public void windowDeiconified(WindowEvent e)
{}
public void windowActivated(WindowEvent e)
{}
public void windowDeactivated(WindowEvent e)
{}
}
Regarding
The first error I'm running into is "cannot find symbol method read()" and "cannot find symbol method write()".
You're calling a method on ArrayList, read(), that just doesn't exist. You need to call this method on one of the contents of the ArrayList, not the ArrayList itself. It's like trying to make an omelette with an egg crate -- won't work. You need to use an egg or two instead. Same thing for write().
Regarding
The second error is in the action listener for display contacts stating that "an array is required but a Contact was found".
You should tell us which line causes this error.
Edit
You show:
for (int i = 0; i < contactList.size(); i++)
{
textArea.setText(contact[i].getName() + "," + contact [i].getNumber() + "\n");
}
That code makes no sense. You need to use your list variable, contactList and get its item via the ArrayList get(...) method.
Your code suggests that you're blindly adding a bunch of code regardless of errors, and that won't work. If you can't use an IDE, you should compile often, after each 1-3 lines and fix all compilation errors before trying to add any more code. Else you'll end up with a rat's nest of errors. Also, read the manual/book. Don't guess at this stuff.
EDIT
I've cleaned up the .equals method for string equality and changed the ContactsCollection initialization to:
public static ArrayList<Contact> contactList = new ArrayList<Contact>();
I've also changed the action performed method in hopes that 'Display contacts' would show more than one contact.
if (contactInput.equals("Display contacts"))
{
ContactsCollection.read();
for (int i = 0; i < contactList.size(); i++)
{
contact = (Contact)contactList.get(i);
for (int j =0; j < contactList.size(); j++)
{
textArea.append(contact.getName() + "," + contact.getNumber() + "\n");
}
}
}
Ultimately the .dat file is written but does not contain any data that is added through the GUI.
END EDIT
I am writing a mock cellphone GUI that acts as a very basic contacts manager. There are several other classes that do not deal with the ArrayList that are working as intended.
When attempting to add a contact to the file I receive a null pointer exception at line 13 of the ContactsCollection class:
for (int i = 0; i < contactList.size(); i++)
and line 93 of the Contacts (GUI) class:
contactList.add(contact);
I have a feeling that I did something wrong when coding the Contacts and ContactsCollection classes. I'm hoping the program to run as follows: The user clicks add contact and enters the information which becomes an object Contact and is added to the contactList ArrayList and written (serialized) to a file "contactList.dat". When the user clicks display contacts the file is read in and each contact is displayed in GUI.
I think that there are several issues with the way I set up the ArrayList, but I think I'm very close to having the program run as I had hoped. Any help is greatly appreciated!
Contacts class:
import java.util.*;
import java.io.*;
public class Contact implements Serializable
{
public static final long serialVersionUID = 42L;
public String name, number;
Contact()
{
name = "No name";
number = "No number";
}
Contact (String theName, String theNumber)
{
this.name = theName;
this.number = theNumber;
}
public void setName(String aName)
{
this.name = aName;
}
public void setNumber(String aNumber)
{
this.number =aNumber;
}
public String getName()
{
return name;
}
public String getNumber()
{
return number;
}
public String toString()
{
return name + ": " + number;
}
public boolean equals(Contact other)
{
if (name.equals(other.getName()) && number.equals(other.getNumber()))
{
return(true);
}
else
{
return(false);
}
}
}
Contacts Collection class
import java.io.*;
import java.util.*;
class ContactsCollection
{
public static ArrayList<Contact> contactList;
public static void write()
{
try
{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("contactList.dat"));
for (int i = 0; i < contactList.size(); i++)
{
out.writeObject(contactList.get(i));
}
out.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
public static void read()
{
contactList = new ArrayList<Contact>();
try
{
ObjectInputStream in = new ObjectInputStream(new FileInputStream("contactList.dat"));
Contact temp;
while (in.available()!=0)
{
temp = (Contact)in.readObject();
contactList.add(temp);
}
in.close();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Contacts (GUI) class
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import javax.swing.Timer;
import java.util.*;
class Contacts extends JFrame implements ActionListener, WindowListener
{
public static final int WIDTH = 400;
public static final int HEIGHT = 600;
public static final int SMALL_WIDTH = 200;
public static final int SMALL_HEIGHT = 100;
private static final Dimension stdBtn = new Dimension(150, 50);
JPanel centerPanel, northPanel, southPanel;
ImageIcon icon;
JLabel picture;
JButton addContact, displayContacts;
JScrollPane scroll;
JTextArea textArea;
Clock clock;
Background background;
Contact contact;
ArrayList<Contact> contactList;
public Contacts()
{
super("Contacts");
this.setLayout(new BorderLayout());
this.setSize(WIDTH, HEIGHT);
this.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
addWindowListener(this);
this.setLocationRelativeTo(null);
centerPanel = new JPanel();
northPanel = new JPanel();
southPanel = new JPanel();
centerPanel.setBackground(Color.BLACK);
southPanel.setBackground(Color.BLACK);
clock = new Clock();
northPanel.add(clock);
icon = new ImageIcon("ContactsBackground.jpg");
picture = new JLabel(icon);
centerPanel.add(picture);
textArea = new JTextArea("", 10, 30);
textArea.setEditable(false);
JScrollPane scroll = new JScrollPane(textArea, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
centerPanel.add(scroll);
JButton displayContacts = new JButton("Display contacts");
displayContacts.addActionListener(this);
southPanel.add(displayContacts);
JButton addContact = new JButton("Add contact");
addContact.addActionListener(this);
southPanel.add(addContact);
this.add(northPanel, BorderLayout.NORTH);
this.add(centerPanel, BorderLayout.CENTER);
this.add(southPanel, BorderLayout.SOUTH);
setResizable(false);
}
public void actionPerformed(ActionEvent e)
{
contactList = new ArrayList<Contact>();
JButton source = (JButton)e.getSource();
String contactInput = source.getText();
if (contactInput == "Display contacts")
{
ContactsCollection.read();
for (int i = 0; i < contactList.size(); i++)
{
contact = (Contact)contactList.get(i);
textArea.setText(contact.getName() + "," + contact.getNumber() + "\n");
}
}
if (contactInput == "Add contact")
{
String name = JOptionPane.showInputDialog(null, "Enter Name");
String number = JOptionPane.showInputDialog(null, "Enter Number");
contact = new Contact(name, number);
contactList.add(contact);
ContactsCollection.write();
}
}
public void windowOpened(WindowEvent e)
{}
public void windowClosing(WindowEvent e)
{
this.setVisible(false);
background = new Background();
background.setVisible(true);
}
public void windowClosed(WindowEvent e)
{}
public void windowIconified(WindowEvent e)
{}
public void windowDeiconified(WindowEvent e)
{}
public void windowActivated(WindowEvent e)
{}
public void windowDeactivated(WindowEvent e)
{}
}
Change
public static ArrayList<Contact> contactList;
to
public static ArrayList<Contact> contactList = new ArrayList<>();
in your version contactList is null because you never initialize it and in the write() method you are trying to call size() on it.
Also, there are some serious flaws in your GUI class (in the actionPerformed() method), read this question to fix them: How do I compare strings in Java?
Also remember that textArea.setText(...) will set the complete text for the textArea, so because this is in a loop in your code, the textArea will contain the output of the last iteration of that loop only. In your case it will be only the last contact.
I have the following code which reads names from the test file, which works fine
public class Names {
Scanner scan;
static String Firstname;
static String Surname;
static String Fullname;
public void OpenFile()
{
try
{
scan = new Scanner(new File("test.txt"));
System.out.println("File found!");
}
catch(Exception e)
{
System.out.println("File not found");
}
}
public void ReadFile()
{
while(scan.hasNext())
{
Firstname = scan.next();
Surname = scan.next();
Fullname = Firstname + " " + Surname;
System.out.println(Fullname);
}
}
public void CloseFile()
{
scan.close();
}
}
Then I have this main class which calls the Names class. it works fine apart from it only shows the last names from the test file.
public class NameSwing implements ActionListener {
private JTextArea tf = new JTextArea(20,20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
static String fullName;
public NameSwing(){
f.add(new JLabel("Name"));
tf.setEditable(true);
f.add(tf);
b.addActionListener(this);
f.add(b);
f.setLayout(new FlowLayout());
f.setSize(300,100);
f.setVisible(true);
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
Names t = new Names();
t.OpenFile();
t.ReadFile();
t.CloseFile();
fullName = Names.Fullname;
}
}
This is the test file content.
Nick Harris
Olly Dean
Emma Sammons
Henry Blackwell
How can I get the textarea to show all of the names from the reader, and not just the last name?
Throw out your Names class as it isn't very helpful and over-uses static fields to its detriment. The best solution in my mind is to:
Create a File that holds your text file
Create a FileReader object with this File
Use this to create a BufferedReader object
call the JTextArea's read(...) method passing in the BufferedReader
And your done.
i.e., in actionPerformed:
BufferedRead buffReader = null;
try {
File file = new File("test.txt");
FileReader fileReader = new FileReader(file);
buffReader = new BufferedReader(fileReader);
tf.read(buffReader, "file.txt");
} catch (WhateverExceptionsNeedToBeCaught e) {
e.printStackTrace();
} finally {
// close your BufferedReader
}
You are using too many static fields for no good reasons. Always use
static fields if you intend to make your class a Factory Class, which
in this case is not appropriate.
You are breaking the fundamental rule of encapsulation, by providing each method with a public Access Specifier, without the need of it.
Instead of calling setSize(), you can simply use pack(), which can determine the dimensions of the Container, in a much better way, than the arbitrary values you had specified.
Please do read about Concurrency in Swing, since appears to me your knowledge is a bit short on that front.
Please do learn Java Naming Conventions.
Moreover, you can simply use a StringBuilder Class, to do this thingy for you. Have a look at the modified code of yours. Do ask anything that is beyond your grasp, I be happy to help on that.
MODIFIED CODE :
import java.io.*;
import java.util.*;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class NameSwing implements ActionListener {
private Names t;
private JTextArea tf = new JTextArea(20,20);
private JFrame f = new JFrame("names");
private JButton b = new JButton("view");
public NameSwing(){
performFileRelatedTask();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel contentPane = new JPanel();
contentPane.setLayout(new BorderLayout(5, 5));
JScrollPane scroller = new JScrollPane();
scroller.setBorder(BorderFactory.createLineBorder(Color.BLUE.darker(), 5));
JPanel centerPanel = new JPanel();
centerPanel.setLayout(new BorderLayout(5, 5));
centerPanel.add(new JLabel("Name", JLabel.CENTER), BorderLayout.PAGE_START);
tf.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
tf.setEditable(true);
centerPanel.add(tf, BorderLayout.CENTER);
scroller.setViewportView(centerPanel);
JPanel footerPanel = new JPanel();
b.addActionListener(this);
footerPanel.add(b);
contentPane.add(scroller, BorderLayout.CENTER);
contentPane.add(footerPanel, BorderLayout.PAGE_END);
f.setContentPane(contentPane);
f.pack();
f.setLocationByPlatform(true);
f.setVisible(true);
}
private void performFileRelatedTask()
{
t = new Names();
}
#Override
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==b)
{
tf.setText(t.getFullNames().toString());
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
SwingUtilities.invokeLater(new Runnable()
{
#Override
public void run()
{
new NameSwing();
}
});
}
}
class Names {
private Scanner scan;
private String firstname;
private String surname;
private StringBuilder fullnames;
public Names()
{
fullnames = new StringBuilder();
openFile();
readFile();
closeFile();
}
public StringBuilder getFullNames()
{
return fullnames;
}
private void openFile()
{
try
{
scan = new Scanner(new File("test.txt"));
System.out.println("File found!");
}
catch(Exception e)
{
System.out.println("File not found");
}
}
private void readFile()
{
while(scan.hasNext())
{
firstname = scan.next();
surname = scan.next();
fullnames.append(firstname + " " + surname + "\n");
}
}
private void closeFile()
{
scan.close();
}
}
The problem is at line
Fullname = Firstname + " " + Surname;.
Make it
Fullname += Firstname + " " + Surname; + "\n"
You problem is solved :)
Here you need the change
while(scan.hasNext())
{
Firstname = scan.next();
Surname = scan.next();
//Assigning each time instead of append
Fullname = Firstname + " " + Surname;
}
Here is complete fix:
public class NameSwing implements ActionListener {
private JTextArea textArea = new JTextArea(20, 20);
private JFrame frame = new JFrame("Names");
private JButton btnView = new JButton("View");
private Scanner scanner;
private String firstName;
private String surName;
private String fullName;
public NameSwing() {
frame.add(new JLabel("Name"));
textArea.setEditable(true);
frame.add(textArea);
btnView.addActionListener(this);
frame.add(btnView);
frame.setLayout(new FlowLayout());
frame.setSize(300, 100);
frame.setVisible(true);
}
public void OpenFile() {
try {
scanner = new Scanner(new File("test.txt"));
System.out.println("File found!");
} catch (Exception e) {
System.out.println("File not found");
}
}
public void ReadFile() {
while (scanner.hasNext()) {
firstName = scanner.next();
surName = scanner.next();
// assign first time
if( fullName == null ) {
fullName = firstName + " " + surName;
} else {
fullName = fullName + "\n" + firstName + " " + surName;
}
System.out.println(fullName);
}
}
public void CloseFile() {
scanner.close();
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btnView) {
textArea.setText(fullName);
}
}
public static void main(String[] args) throws FileNotFoundException, IOException {
NameSwing nameSwing = new NameSwing();
nameSwing.OpenFile();
nameSwing.ReadFile();
nameSwing.CloseFile();
}
}