How do I rewrite an existing file in a Java program? - java

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());
}

Related

Java Contact Book - Ability to save and Load

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();
}
}}

Creating multiple choice for user

I'm trying to make a game where you have to login with certain credentials and after that the user is given a choice between 2 games. I am able to code the games but am stuck at making the input for choice between games. Any help is appreciated! (It's the very last line that seems to not work, I have no idea why).
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class SkillsDemo3 {
boolean again = true;
int action;
public static void main(String[] args) throws IOException {
//***************************
//Login
//***************************
class User {
User (String username, String password) {
this.username = username;
this.password = password;
}
String GetUsername() { return username; }
String GetPassword() { return password; }
private String username;
private String password;
}
String greeting = "Hello";
String username;
String password;
// Used to hold the instance of a user who successfully logged in
User loggedInUser = null;
// Create an empty list to hold users
List<User> listOfUsers = new ArrayList<>();
// Add 3 users to the list
listOfUsers.add(new User("Gerry","spintown"));
listOfUsers.add(new User("Evelyn","poker"));
listOfUsers.add(new User("Joan","bonus"));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n");
System.out.println(greeting);
System.out.println("Please type your username :");
username = br.readLine();
System.out.println("Please type your password :");
password = br.readLine();
for (User user : listOfUsers) {
if (user.GetUsername().equals(username)) {
if (user.GetPassword().equals(password)) {
loggedInUser = user;
// when a user is found, "break" stops iterating through the list
break;
}
}
}
// if loggedInUser was changed from null, it was successful
if (loggedInUser != null) {
System.out.println("User successfully logged in: "+loggedInUser.GetUsername());
} else {
System.out.println("Invalid username/password combination");
}
//**********************************
//Choice of Games
//**********************************
boolean again = true;
int action = 0;
if (action == 1) {
System.out.println("\nYou have chosen to play Rock, Paper, Scissors");
} else if (action == 2) {
System.out.println("\nYou have chosen to Play pick up sticks");
again = false;
}
SkillsDemo3 what = new SkillsDemo3();
while (what.again) {
System.out.println("Please type 0 to continue or 1 to stop :");
what.action = Integer.parseInt(br.readLine());
System.out.println("You typed : "+what.action);
what.SkillsDemo3();
}
}
}
You don't need an object of your class SkillsDemo3
Just make the variables action and again static and get your workflow right. I tried to implement some workflow but i don't know if this fits for you.
public class SkillsDemo3 {
private static boolean again = true;
private static int action;
public static void main(String[] args) throws IOException {
//***************************
//Login
//***************************
class User {
User (String username, String password)
{
this.username = username;
this.password = password;
}
String GetUsername() {return username;}
String GetPassword() {return password;}
private String username;
private String password;
}
String greeting = "Hello";
String username;
String password;
// Used to hold the instance of a user who successfully logged in
User loggedInUser = null;
// Create an empty list to hold users
List<User> listOfUsers = new ArrayList<>();
// Add 3 users to the list
listOfUsers.add(new User("Gerry","spintown"));
listOfUsers.add(new User("Evelyn","poker"));
listOfUsers.add(new User("Joan","bonus"));
BufferedReader br = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("*** Welcome to the program ***\n");
System.out.println(greeting);
System.out.println("Please type your username :");
username = br.readLine();
System.out.println("Please type your password :");
password = br.readLine();
for (User user : listOfUsers)
{
if (user.GetUsername().equals(username))
{
if (user.GetPassword().equals(password))
{
loggedInUser = user;
// when a user is found, "break" stops iterating through the list
break;
}
}
}
// if loggedInUser was changed from null, it was successful
if (loggedInUser != null)
{
System.out.println("User successfully logged in: "+loggedInUser.GetUsername());
}
else
{
System.out.println("Invalid username/password combination");
}
//**********************************
//Choice of Games
//**********************************
again = true;
action = 0;
while (again)
{
System.out.println("Please type 1 for Rock, Paper, Scissors or 2 for Play pick up sticks:");
action = Integer.parseInt(br.readLine());
if (action == 1)
{
System.out.println("\nYou have chosen to play Rock, Paper, Scissors");
}
else if (action == 2)
{
System.out.println("\nYou have chosen to Play pick up sticks");
again = false;
}
System.out.println("Please type 0 to continue or 1 to stop :");
action = Integer.parseInt(br.readLine());
again = action == 0;
System.out.println("You typed : "+action);
}
}
}

Library System Login Logout

class Test{
public static void main(String args[])
{
Patron list[] = new PatronData().getPatronData();
/*for(Patron p: list)
{
System.out.println(p);
}*/
}
}
class PatronData{
//Patron patron[] = {new Patron("Daniel","A001","15WAD00001","A4701,Jalan Kepong, Pahang","JK01",0.00,"012-8765432"),
// new Patron("Chiam","A002","15WAD00002","A4702,Jalan Akar,Pahang","JK02",0.00,"0102288554")};
Patron patron[] = new Patron[2];
public Patron[] getPatronData()
{
patron[0] = new Patron("Daniel","A001","15WAD00001","A4701,Jalan Kepong, Pahang","JK01",0.00,"012-8765432");
patron[1] = new Patron("Chiam","A002","15WAD00002","A4702,Jalan Akar,Pahang","JK02",0.00,"0102288554");
return patron;
}
}
class Patron{
private String userName;
private String password;
private String userCode;
private String streetAddress;
private String postCode;
private double overdueBalance;
private String phoneNumber;
Patron(String userName[], String password[], String userCode,
String streetAddress, String postCode, double overdueBalance, String phoneNumber)
{
this.userName = userName;
this.password = password;
this.userCode = userCode;
this.streetAddress = streetAddress;
this.postCode = postCode;
this.overdueBalance = overdueBalance;
this.phoneNumber = phoneNumber;
int logNMatch = 0;
Scanner scan = new Scanner(System.in);
do{
System.out.print("Please Enter Your User Name > ");
String inputUserName=scan.nextLine();
System.out.println();
System.out.print("Please Enter Your Password > ");
String inputPassword = scan.nextLine();
if(userName.compareTo(inputUserName) == 0 && password.compareTo(inputPassword) == 0)
{
System.out.println("Logging Successful");
System.out.print("\n\n");
}
else
{
System.out.println("Loging fail");
System.out.println("Please again later");
logNMatch++;
}
}while(logNMatch > 0);
}
}
Hey guys, I am learning Java in Diploma Level. I have a question.
Please, I have no idea why I cannot straight away logging into "Chiam Account"I expected is when i log in the compiler will automatically check whether is the login detail match with the data in library system.
You are requesting the login information inside the constructor. Meaning that whenever you make a new Patron it will prompt you to login with that user's information.
Instead remove everything inside that do/while loop and add a method like loginFromLibrary() that will prompt the user to input their name and password. Then check all of the Patrons to see if any of their names match the username given. Then just make sure that the username matches the password.
This example will require some getter (getPassword() and getUsername()):
public void loginFromLibrary(Patron[] patrons){
Scanner scan = new Scanner(System.in);
while (true){
// get usernmae
System.out.println("Username > ");
String username = scan.nextLine();
Patron user = null;
// check array to see if username exists
for (Patron p : patrons){
if (p.getUsername().equals(username)){
user = p;
break;
}
}
if (user == null){
// username not found
System.out.println("Username not found");
continue;
}
// get password
System.out.println("Password > ");
String pass = scan.nextLine();
// check password
if (pass.equals(user.getPassword())){
// logged in
break;
} else {
// wrong password
}
}
scan.close();
}

Why can't I store data inside my .txt file?

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 from a saved text file?

*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 .

Categories

Resources