I am working on a project which allows a user to add a new contact, update an existing contact, remove a contact, list all contacts, save contacts and load contacts. The program I have created works for adding, listing, updating and removing. When implementing the save and l0oad classes I need to catch an IOExceptions and present to the user. Currently the code I have written is erroring for:
When selection option 5 to Save IO am getting the following error:
Enter the filename to save: Exception in thread "main" java.lang.NoSuchMethodError: 'void com.mycompany.cousinj6.ContactApp.ContactFileManager.writeContacts(java.lang.String, com.mycompany.cousinj6.ContactApp.Contact[])'
at com.mycompany.cousinj6.ContactApp.ContactBook.save(ContactBook.java:41)
at com.mycompany.cousinj6.ContactApp.ContactApp.main(ContactApp.java:93)
Command execution failed.
Presented in the ContactBook class load method.
How do I refactor this code to remove these error and allow the program to compile?
Contact
import java.io.Serializable;
public class Contact implements Serializable {
private String name;
private String address;
private String phone;
private String email;
public Contact(String name, String address, String phone, String email) {
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
String s = new String().format("%-20s%-20s%-20s%-20s\n",name,address,phone,email);
return s;
}}
ContactBook
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class ContactBook {
private final ArrayList<Contact> entries;
private final ContactFileManager fileMan;
public ContactBook() {
entries = new ArrayList<>();
fileMan = new ContactFileManager();
}
public void add(Contact contact) {
entries.add(contact);
}
public void update(int index, Contact contact) {
entries.set(index, contact);
}
public void remove(int index) {
entries.remove(index);
}
public void save(String filename, Scanner sc) {
try {
//Create a contact array object with the same size as the
entries arraylist object
Contact[] contacts = new Contact[entries.size()];
//Convert the entries arraylist object to a contact array
object using the toArray method
contacts = entries.toArray(contacts);
//Supply the correct parameters to the writeContacts method
ContactFileManager.writeContacts(filename, contacts);
} catch (IOException e) {
System.out.println("Unable to save: " + e.getMessage());
}
}
public void load (String filename, Scanner sc) {
try {
entries.clear();
//Convert the contact[] array object to List
object(Collection type object)
List<Contact> contacts =
Arrays.asList(ContactFileManager.readContacts(filename));
//Then supply the collection object of type List to the
entries
entries.addAll(contacts);
} catch (IOException | ClassNotFoundException e) {
System.out.println("Unable to load: " + e.getMessage());
}
}
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < entries.size(); i++) {
sb.append(i +
1).append(".\t").append(entries.get(i).toString()).append("\n");
}
return sb.toString();
}}
ContactFileManager
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class ContactFileManager {
public static void writeContacts(String fileName, Contact[]
contacts) throws IOException
{
FileOutputStream fos = new FileOutputStream(fileName);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(contacts);
oos.close();
fos.close();
}
public static Contact[] readContacts(String fileName) throws
IOException,
ClassNotFoundException {
FileInputStream fis = new FileInputStream(fileName);
ObjectInputStream ois = new ObjectInputStream(fis);
Contact[] contacts = (Contact[]) ois.readObject();
ois.close();
fis.close();
return contacts;
}}
ContactApp
import java.util.Scanner;
public class ContactApp {
public static void main(String[] args) {
//Declaing variables
int choice;
String name, address, phone, email;
Scanner sc = new Scanner(System.in);
ContactBook book = new ContactBook();
choice = 0;
while (choice != 5) {
System.out.println("1. List all Contacts");
System.out.println("2. Add a new Contact");
System.out.println("3. Update an existing Contact");
System.out.println("4. Remove a Contact");
System.out.println("5. Save Contact Book");
System.out.println("6. Load Contact Book");
System.out.println("7. Quit");
System.out.print("Enter your choice: ");
choice = sc.nextInt();
switch (choice) {
case 1: {
System.out.println(book.toString());
continue;
}
case 2: {
sc.nextLine();
System.out.print("Enter a name: ");
name = sc.nextLine();
System.out.print("Enter an address :");
address = sc.nextLine();
System.out.print("Enter a phone number :");
phone = sc.nextLine();
System.out.print("Enter an email address :");
email = sc.nextLine();
book.add(new Contact(name, address, phone, email));
continue;
}
case 3: {
System.out.println(book.toString());
System.out.print("Enter index of Contact to update: ");
int index = sc.nextInt();
sc.nextLine();
System.out.print("Enter a new name: ");
name = sc.nextLine();
System.out.print("Enter a new address :");
address = sc.nextLine();
System.out.print("Enter a new phone number :");
phone = sc.nextLine();
System.out.print("Enter a new email address :");
email = sc.nextLine();
book.update(index - 1, new Contact(name, address, phone, email));
continue;
}
case 4: {
System.out.println(book.toString());
System.out.print("Enter position number to delete: ");
int index = sc.nextInt();
book.remove(index - 1);
continue;
}
case 5: {
System.out.print("Enter the filename to save: ");
String filename = sc.nextLine();
book.save(filename, sc);
continue;
}
case 6: {
System.out.print("Enter the filename to load: ");
String filename = sc.nextLine();
book.load(filename, sc);
continue;
}
case 7: {
continue;
}
default: {
System.out.println("** Invalid Choice. Please try again.");
}
}
sc.close();
}
}}
Related
I have this in the Class: public static ArrayList<String> studentInfo = new ArrayList<String>();I created a method CreateStudent() that basically allows the user to create a student using Scanner, the DisplayStudent() uses ObjectInputStream to open the file and read the data. Now, when the users creates a student, it stores the data into an ArrayList using studentInfo.add(), the idea is that the EditStudent() access the data added into the ArrayList with the info added in CreateStudent() Is there a way to access that list from another method?I would appreciate any ideas, here is my code:
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.io.*;
import java.lang.ClassNotFoundException;
public class MidTermProject extends ObjectOutputStream {
private boolean append;
private boolean initialized;
private DataOutputStream dout;
static AtomicInteger idGenerator = new AtomicInteger(0001);
static int id;
public static String FullName;
public static String address;
public static String city;
public static String state;
public static String className;
public static String instructor;
public static String department;
public static String classNumber;
public static String courseNumber;
public static String year;
public static String semester;
public static String grade;
public static String studentID;
public static String courseID;
public static String enrollmentID;
public static ArrayList<String> studentInfo = new ArrayList<String>();
Scanner keyboard = new Scanner(System.in);
protected MidTermProject(boolean append) throws IOException, SecurityException {
super();
this.append = append;
this.initialized = true;
}
public MidTermProject(OutputStream out, boolean append) throws IOException {
super(out);
this.append = append;
this.initialized = true;
this.dout = new DataOutputStream(out);
this.writeStreamHeader();
}
#Override
protected void writeStreamHeader() throws IOException {
if (!this.initialized || this.append) return;
if (dout != null) {
dout.writeShort(STREAM_MAGIC);
dout.writeShort(STREAM_VERSION);
}
}
public static int getId() {
return id;
}
///Create Student Method
public static void CreateStudent() throws IOException {
File file = new File("StudentInfo.dat");
boolean append = file.exists();
Scanner keyboard = new Scanner(System.in);
try (
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
) {
id = idGenerator.getAndIncrement();
studentID = Integer.toString(getId());
oout.writeObject("Student ID: " + studentID);
System.out.print("\nPlease enter your information bellow.\n" + "\nFull Name: ");
FullName = keyboard.nextLine();
oout.writeObject("Full Name: " + FullName);
System.out.print("Address: ");
address = keyboard.nextLine();
oout.writeObject("Address: " + address);
System.out.print("City: ");
city = keyboard.nextLine();
oout.writeObject("City: " + city);
System.out.print("State: ");
state = keyboard.nextLine();
oout.writeObject("State: " + state + "\n");
studentInfo.add(studentID);
studentInfo.add(FullName);
studentInfo.add(address);
studentInfo.add(city);
studentInfo.add(state);
oout.close();
System.out.println("Done!\n");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
///Edit Student Method
public static void EditStudent() throws IOException {
String editName;
String editaddress;
String editCity;
String editState;
int editID;
String editStudent;
boolean endOfFile = false;
Scanner keyboard = new Scanner(System.in);
System.out.print(studentInfo);
System.out.print("Enter the ID of the student you would like to edit: ");
editID = keyboard.nextInt();
String editingID = Integer.toString(editID);
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
File file = new File("StudentInfo.dat");
boolean append = file.exists();
while(!endOfFile)
{
try
{
FileOutputStream fout = new FileOutputStream(file, append);
MidTermProject oout = new MidTermProject(fout, append);
editStudent = (String) inputFile.readObject();
if(editingID == oout.studentID) {
System.out.print("\nPlease enter NEW information bellow.\n" + "\nFull Name: ");
editName = keyboard.nextLine();
oout.writeObject("Full Name: " + editName);
System.out.print("Address: ");
editaddress = keyboard.nextLine();
oout.writeObject(editaddress);
System.out.print("City: ");
editCity = keyboard.nextLine();
oout.writeObject(editCity);
System.out.print("State: ");
editState = keyboard.nextLine();
oout.writeObject(editState);
oout.close();
System.out.print("Successfully Edited");
} else {
System.out.print("Error");
}
}
catch (EOFException | ClassNotFoundException e)
{
endOfFile = true;
}
}
}
Display Student Method
public static void DisplayStudent() throws IOException {
FileInputStream fstream = new FileInputStream("StudentInfo.dat");
ObjectInputStream inputFile = new ObjectInputStream(fstream);
String student;
boolean endOfFile = false;
while(!endOfFile)
{
try
{
student = (String) inputFile.readObject();
System.out.print(student + "\n");
}
catch (EOFException | ClassNotFoundException e)
{
endOfFile = true;
}
}
System.out.println("\nDone");
inputFile.close();
}
I am trying to write a program that manages a Contact List document the user has. The program should prompt the user for the file they wish to import, then give them options to display the contact list, add a contact, remove a contact, and save the current version of the contact. Everything in my code works up until I try to output the file. I get a "FileNotFoundException (too many files in system)". Below is my code so far:
import java.io.*;
import java.util.Scanner;
import java.util.TreeMap;
public class ContactList {
public static void main (String [] args) throws IOException
{
String contactFile = null;
Scanner input = new Scanner(System.in);
System.out.print("Enter name of contact file: ");
contactFile = input.next();
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(contactFile)));
TreeMap< String, String > contacts = new TreeMap< String, String >();
Contact contact = new Contact();
br.close();
menu();
int userChoice = input.nextInt();
while (userChoice != 4)
{
if (userChoice == 1)
{
menu();
userChoice = input.nextInt();
}
if (userChoice == 2)
{
System.out.print("Number of contacts to add: ");
int numContacts = input.nextInt();
for (int i = 0; i < numContacts; i++)
{
contact.setName(input.nextLine());
System.out.print("Enter contact's name (Last name, First name): ");
contact.setName(input.nextLine());
contact.setPhoneNumber(input.nextLine());
System.out.print("Enter contact's phone number (xxx-xxx-xxxx): ");
contact.setPhoneNumber(input.nextLine());
contact.setEmail(input.nextLine());
System.out.print("Enter contact's email (ex. johndoe#gmail.com): ");
contact.setEmail(input.nextLine());
contacts.put(contact.getName(), contact.remainingInfo());
}
menu();
userChoice = input.nextInt();
}
if (userChoice == 3)
{
System.out.print("Enter name of contact you wish to remove (Last name, First name): ");
contacts.remove(input.nextLine());
menu();
userChoice = input.nextInt();
}
}
if (userChoice == 4)
{
PrintWriter outFile = new PrintWriter(contactFile);
outFile.print(contacts.entrySet());
}
}
public static void menu()
{
System.out.println("1 Display Contact List");
System.out.println("2 Add a Contact");
System.out.println("3 Remove a Contact");
System.out.println("4 Save Contact List and Exit");
System.out.print("Command: ");
}
}
And the Contact class, if it's needed:
public class Contact {
private String name;
private String phoneNumber;
private String email;
public void setName(String name) {
this.name = name;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public void setEmail(String email) {
this.email = email;
}
public String getName()
{
return name;
}
public String remainingInfo()
{
return phoneNumber + " " + email;
}
}
Is there a way to import a file, make changes, overwrite that file, and output/save it? I thought that outputting the edited file to the same location would overwrite it, but apparently not.
Update: The exact error message I get reads:
Exception in thread "main" java.io.FileNotFoundException: /Users/jesbarba/Desktop/Contacts.txt (Too many open files in system)
at java.io.FileOutputStream.open0(Native Method)
at java.io.FileOutputStream.open(FileOutputStream.java:270)
at java.io.FileOutputStream.<init>(FileOutputStream.java:213)
at java.io.FileOutputStream.<init>(FileOutputStream.java:101)
at java.io.PrintWriter.<init>(PrintWriter.java:184)
at ContactList.main(ContactList.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
This is when using intelliJ
you need to wrap your BufferedReader br and your PrintWriter outFile into a try-with-resources statement as next because otherwise you never close your files properly which can be an issue especially on Windows OS:
try (PrintWriter outFile = new PrintWriter(contactFile)) {
outFile.print(contacts.entrySet());
}
I have a text file that looks like this.
BEGINNING OF LIST
Name: Janet
Age: 21
Birthday month: April
END OF LIST
BEGINNING OF LIST
Name: Peter
Age: 34
Birthday month: January
END OF LIST
So I want to grab info and put it into an object array. it is an extensive list and I am using the delimiters beginning of list and end of list to delimit the content.
How can I store these items in an object array?
I would suggest you create a class first for storing the information, with name, age, and birthday month attributes. It's a very good practice to override the toString() method so you can print out the class neatly.
Then you can check for each line whether it contains information about the name, age, or birthday month through splitting each line into an array of words, and checking for the information.
Once the line reads "END OF LIST", you can add a class Person with the parameters to the ArrayList.
For the example I used "people.txt" as the file (make sure you place the text document outside of the src folder which contains your .java files).
Main.java
import java.io.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String[] args)
{
BufferedReader bufferedReader = null;
FileReader fileReader = null;
String name = null;
String age = null;
String month = null;
List<Person> people = new ArrayList<Person>();
try
{
String fileName = "people.txt";
fileReader = new FileReader(fileName);
bufferedReader = new BufferedReader(fileReader);
String line = null;
while ((line = bufferedReader.readLine()) != null)
{
String[] information = line.split(" ");
if (Arrays.asList(information).contains("Name:"))
{
name = information[1];
}
if (Arrays.asList(information).contains("Age:"))
{
age = information[1];
}
if (Arrays.asList(information).contains("month:"))
{
month = information[2];
}
if (line.equals("END OF LIST"))
{
people.add(new Person(name, age, month));
name = "";
age = "";
month = "";
}
}
for (Person person : people)
{
System.out.println(person);
System.out.print("\n");
}
}
catch (FileNotFoundException e)
{
System.out.println(e.getMessage());
}
catch (IOException ex)
{
System.out.println("Error reading people.txt");
}
finally
{
if (bufferedReader != null)
{
try
{
bufferedReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
if (fileReader != null)
{
try
{
fileReader.close();
}
catch (IOException ex)
{
System.out.println(ex.getMessage());
}
}
}
}
}
Person.java
public class Person {
private String name;
private String age;
private String birthday;
public Person(String name, String age, String birthday)
{
this.name = name;
this.age = age;
this.birthday = birthday;
}
#Override
public String toString()
{
String information = "Name: " + name + "\nAge: " + age + "\nBirthday: " + birthday;
return information;
}
}
This is a workout app that I'm working on. The idea is to create an account(text file) and store the data that you enter inside it. Here's what I have so far.
public static void main(String[] args) {
boolean start = true;
while (start == true) {
CreateNewMember();
start = DecideToAddOrQuit();
}
}
public static void CreateNewMember() {
Scanner keyboard = new Scanner(System.in);
out.println("Enter a username: ");
String input = keyboard.nextLine();
createMember member = new createMember(input);
member.setMembership();
member.setInfo();
}
public static boolean DecideToAddOrQuit() {
Scanner keyboard = new Scanner(System.in);
out.println("\nPress 1 if you want to continue adding data.");
out.println("Press any other key if you want to leave.");
String decision = keyboard.nextLine();
if (decision.equals("1")) {
out.println("");
return true;
} else {
out.println("Goodbye!");
return false;
}
}
And here's the class responsible for adding data to the file:
public class createMember {
public String name;
private String fullName;
private String age;
private String experience;
private Formatter x;
public createMember(String name) {
this.name = name;
}
public void setMembership() {
try {
x = new Formatter(name);
out.println("File with name \"" + name + "\" has been created!");
} catch (Exception e) {
out.println("Could not create username.");
}
}
public void setInfo () {
Scanner keyboard = new Scanner(System.in);
String fullNameIn, ageIn, experienceIn;
out.println("Enter your Full Name");
fullNameIn = keyboard.nextLine();
fullName = fullNameIn;
out.println("Enter your Age");
ageIn = keyboard.nextLine();
age = ageIn;
out.println("Enter your lifting experience\n");
experienceIn = keyboard.nextLine();
experience = experienceIn;
x.format("%s\t%s\t%s", fullName, age, experience );
}
}
The values that I enter(fullName, age, experience) are NOT stored in the username file. How do I fix this and why is it occuring?
If you are expecting output to be written as the program is running, you may not see it because Formatter buffers the output.
You must close() the file when you are done with it (x.close()) so that any remaining buffered data is written (this does not happen automatically, even on program exit). Also if you want the output to actually be written immediately, flush() it as soon as you write a line (x.flush()).
This question is not the clearest, but as far is I'm concerned you haven't ever told anything to actually write the data to a file at all. You should use PrintWriter. This will load the data you want into the file. Plus, in your code, your file is never created.
import java.io.PrintWriter;
public class createMember {
public String name;
private String fullName;
private String age;
private String experience;
// private Formatter x; not quite sure what this does. There seems to be no need for it.
PrintWriter write;
File f;
public createMember(String name) {
this.name = name;
}
public void setMembership() throws Exception {
try {
// x = new Formatter(name);
f = new File (name);
f.createNewFile(); // This throws a HeadlessException (i believe, as it might be a FileNotFoundException instead)
out.println("File with name \"" + name + "\" has been created!");
} catch (Exception e) {
out.println("Could not create username.");
}
}
public void setInfo () throws Exception {
Scanner keyboard = new Scanner(System.in);
String fullNameIn, ageIn, experienceIn;
write = new PrintWriter(f.toString()); // This throws a FileNotFoundException
out.println("Enter your Full Name");
fullNameIn = keyboard.nextLine();
fullName = fullNameIn;
write.println (fullName);
out.println("Enter your Age");
ageIn = keyboard.nextLine();
age = ageIn;
write.println(age);
out.println("Enter your lifting experience\n");
experienceIn = keyboard.nextLine();
experience = experienceIn;
write.println(experience);
//x.format("%s\t%s\t%s", fullName, age, experience );
write.close(); // Be sure to close it, or it gives a warning and the file is never written.
}
}
I hope this is what you're looking for and happy coding!
*How to increment a number read from a saved text file?
I'm trying to add an account Number read from a file to an array and when I add a new data to the array the account number should be auto increment of the existing account number. The problem with my code is that it woks fine until i save it to a file. When I re-open the application the account number starts back from the beginning i.e if the saved acc number is 100,101 when I re-open the application the acc number starts from 100 again.
Please can any one Help Me read from the file and then write it back to file.*
The array is starting from the beginning when restart the application.But I was just wondering If any one can help me to find a solution for this
This is my code
import java.io.Serializable;
public class Student implements Serializable {
//--------------------------------------------------------------------------
protected static int nextBankID=1000;
protected int accountNumber;
protected String fname;
protected String lname;
protected String phone;
//--------------------------------------------------------------------------
//constructor
public Student(String fname, String lname, String phone){
this.accountNumber = nextBankID++;
this.fname = fname;
this.lname = lname;
this.phone=phone;
}
//--------------------------------------------------------------------------
public void setFname(String fname) {
this.fname = fname;
}
//--------------------------------------------------------------------------
public void setLname(String lname) {
this.lname = lname;
}
//--------------------------------------------------------------------------
public void setPhone(String phone) {
this.phone = phone;
}
//--------------------------------------------------------------------------
public int getAccountNumber() {
return accountNumber;
}
//--------------------------------------------------------------------------
public void setAccountNumber(int accountNumber) {
this.accountNumber = accountNumber;
}
//--------------------------------------------------------------------------
public String getFname() {
return fname;
}
//--------------------------------------------------------------------------
public String getLname() {
return lname;
}
//--------------------------------------------------------------------------
public String getPhone() {
return phone;
}
#Override
public String toString(){
return "\n #Acc\tFirst Name"+"\tLast Name\t#Phone"
+ "\tBalance"+ "\tOverdraft\t\t\n"+accountNumber+""
+ "\t"+fname+"\t"+lname+"\t"+phone;
}
}
//-------------------------------------------------------
import java.io.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
#SuppressWarnings("unchecked")
public class ReadWrite{
//save stuAccount ArrayList will all stuAccount objects to file
public static void writeAccounts(String fileName,ArrayList<Student> stu) {
//Create a stream between the program and the file
try
{
FileOutputStream foStream = new FileOutputStream(fileName);
ObjectOutputStream outStream = new ObjectOutputStream(foStream);
outStream.writeObject(stu);
outStream.close();
}
catch(FileNotFoundException fnfEx)
{
JOptionPane.showMessageDialog(null,fnfEx.getMessage());
}
catch(IOException ioE)
{
JOptionPane.showMessageDialog(null,ioE.getMessage());
}
}
//read stuAccount ArrayList
public static ArrayList<Student> readAccounts(String fileName,ArrayList<Student> stu){ //throws IOException
try
{
//JOptionPane.showMessageDialog(null, "Enter subject details to display");
//StudentDriver.createSubject(); //create a subject to store stuAccount objects
FileInputStream fiStream = new FileInputStream(fileName);
ObjectInputStream inStream = new ObjectInputStream(fiStream);
stu = (ArrayList<Student>)inStream.readObject();
//© Increment's the stu account with 1
for (int i=0; i< stu.size(); i++){
Object b1 = stu.get(i);
if (b1 instanceof Student){
Student bAccount = (Student)b1;
if(bAccount.accountNumber==stu.get(i).getAccountNumber())
bAccount.accountNumber=stu.get(i).getAccountNumber();
}
}//for the next user entry
inStream.close();
}
catch(ClassNotFoundException cnfEx){
JOptionPane.showMessageDialog(null,cnfEx.getMessage());
}
catch(FileNotFoundException fnfEx){
JOptionPane.showMessageDialog(null,fnfEx.getMessage());
}
catch(IOException ioE){
JOptionPane.showMessageDialog(null,ioE.getMessage());
}
JOptionPane.showMessageDialog(null, ""+stu.size()
+ " stu account(s) found in the database....");
return stu; //return read objects to Driver class
}
}
// ----------------------------------------------
import java.awt.Font;
import java.io.IOException;
import java.util.ArrayList;
import javax.swing.JOptionPane;
import javax.swing.JTextArea;
public class StudentDriver {
public static ArrayList<Student> stu = new ArrayList<>();
private static String fileName = "student.txt";
//------------------------------------------------------------------------------
public static void main(String [] vimal) throws IOException{
try{
stu = ReadWrite.readAccounts(fileName,stu);
if(stu.isEmpty()){
JOptionPane.showMessageDialog(null,"No account's found "
+ "in the datbase to load into memory!\n\n");
}else{
JOptionPane.showMessageDialog(null,"File contents "
+ "read and loaded into memory!\n");
}
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Error encountered "
+ "while opening the file"
+ "\nCould not open file"
+ "\n" + e.toString());
}
//Initialise Main Menu Choice;
//------------------------------------------------------------------------------
int choice= mainMenu();
while (choice!=3){
switch (choice){
case 1:
createStudentAccount();//a new account Menu
break;
case 2:
list();//list method
break;
case -100:
JOptionPane.showMessageDialog(null,"You have selected cancel");
break;
case -99:
JOptionPane.showMessageDialog(null,"You must select 1-3");
break;
default:
JOptionPane.showMessageDialog(null,"Not a valid option .Plese"
+ " re-enter your option");
break;
}//END FO SWITCH STATEMENT
choice = mainMenu();
}//END OF WHILE LOOP
ReadWrite.writeAccounts(fileName,stu); //save ArrayList contents before exiting
System.exit(0);
}
//END MAIN , PROGRAM EXITS HERE
public static int mainMenu(){
String menu="US COLLEGE\n Main menu\n1.Add New Student\n2. Print All\n3. Exit\n\n";
String userSelection = (String)JOptionPane.showInputDialog(null,menu);
int option = validateSelection(userSelection);
return option;
}
//------------------------------------------------------------------------------
// CREATE ACCOUNT MENU SELECTION VALIDATION
public static int validateSelection(String createAccount){
//enter cancel
if (createAccount==null)
return-100;
//hit enter without entry = zero-length string
if (createAccount.length()<1)
return-99;
//entered more than one charecter
if (createAccount.length()>1)
return-101;
if (createAccount.charAt(0)< 49 ||
createAccount.charAt(0)>51)
return-101;
else
return Integer.parseInt(createAccount);
}
public static void createStudentAccount(){
String acctFirstName,acctLastName,strPhone;
try{
//Account name validation
acctFirstName = JOptionPane.showInputDialog(null,"Enter your first name");
acctLastName = JOptionPane.showInputDialog(null,"Enter Your Family Name");
strPhone =JOptionPane.showInputDialog(null,"Enter Your Phone nuber");
stu.add(new Student(acctFirstName,
acctLastName,strPhone));
}
catch(Exception e){}
}
public static void list(){
String accounts = "";
String College="\t======== US College ========\n";
JTextArea output = new JTextArea();
output.setFont(new Font("Ariel", Font.PLAIN, 12));
if(stu.isEmpty()){
JOptionPane.showMessageDialog(null,"No account's created yet");
}
else{
//for each Bank account in BankAccount ArrayList
for (Student s1: stu){
if(stu.isEmpty()){
JOptionPane.showMessageDialog(null,"No account's created yet");
}else{
accounts += s1.toString();
}
output.setText(College+accounts );
}
JOptionPane.showMessageDialog(null,output);
}
}
}
First create a table for maintaing account number.After writing text to the file, every time use to update the table of previous account no to new account no by incrementing the value of account no .