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!
Related
I'm training with Java and this is the first time that I'm using threads with it. An exercise asked me to read from a .cvs file and as a bonus it's asking me to use 3 threads to read this file and save the information in the same ArrayList<CustomClass>. I should have some kind of problem because every thread must read an unique line from the file.
This file contains this:
Clienti
nome,cognome,tipoMezzo,tipoParcheggio,dataOperazione,Operazione
Paolo,Rossi,cabrio,coperto,07/12/2022 09:00,0
Chiara,Bianchi,moto,aperto,07/12/2022 09:01,0
Abbondazio,Addolorata,4x4,aperto,07/12/2022 09:10,0
Agamennone,Agatangelo,moto,coperto,07/12/2022 09:11,0
Aldebrando,Barachisio,berlina,coperto,07/12/2022 09:12,0
Aldighiero,Barbaziano,moto,aperto,07/12/2022 10:01,0
Aldobrando,Bardomiano,moto,coperto,07/12/2022 10:05,0
Angilberto,Barsanufio,cabrio,aperto,07/12/2022 10:06,0
public class CarParkingImpl implements CarParking {
ArrayList<Cliente> lista;
byte coperto;
byte aperto;
public CarParkingImpl(){
coperto=30;
aperto =50;
lista = new ArrayList<Cliente>();
}
//This function must work with 3 operating Threads that read the same .cvs file and are syncronize to read each one a different line and put the information readed in the ArrayList 'lista'
#Override
public void carParkingFromCSV(String filePath) throws FileNotFoundException {
Scanner scan = new Scanner(new File(filePath));
scan.next();
scan.next();
while(scan.hasNext()){
String[] clientInfo1 = scan.next().split(",");
String[] clientInfo2 = scan.next().split(",");
String[] daySplit = clientInfo1[4].split("/");
String[] timeSplit = clientInfo2[0].split(":");
Calendar tempCalendar = Calendar.getInstance();
tempCalendar.set(Integer.parseInt(daySplit[2]),Integer.parseInt(daySplit[1])-1,Integer.parseInt(daySplit[0]),Integer.parseInt(timeSplit[0]),Integer.parseInt(timeSplit[1]));
Cliente tempClient = new Cliente(clientInfo1[0],clientInfo1[1],clientInfo1[2],clientInfo1[3],tempCalendar,Byte.parseByte(clientInfo2[1]));
try {
carParkingClient(tempClient);
}catch (CarParkingIsFullException e){
System.err.println(e.getMessage());
}
}
scan.close();
}
}
public class Cliente {
String name;
String surname;
String carType;
String parkReq;
Calendar dateOperation;
Byte parkOperation;
public Cliente(String name, String surname, String carType, String parkReq, Calendar dateOperation, Byte parkOperation) {
this.name = name;
this.surname = surname;
this.carType = carType;
this.parkReq = parkReq;
this.dateOperation = dateOperation;
this.parkOperation = parkOperation;
}
}
public class Main {
public static void main(String[] args) throws FileNotFoundException {
String path = "Clienti.csv";
String outPath = "Report.txt";
CarParkingImpl carParking = new CarParkingImpl();
try {
carParking.carParkingFromCSV(path);
carParking.printReport(outPath);
}catch (FileNotFoundException e){
System.err.println(e.getMessage());
}catch (IOException e){
System.err.println(e.getMessage());
}
}
}
As a part of my assignment I had to store objects of an array in a flat-file and retrieve them when certain criteria was met. I can save the objects fine but when retrieving them I have an issue with getting more than one value, I understand what is going wrong but I am struggling to find a solution. Here is the concept of whats happening.
Button no 10,A (R1S10 in the code)is my testing button, When I click it it creates an event that I will show below.
Click event for button 10A -
private void R1S10ActionPerformed(java.awt.event.ActionEvent evt) {
seats.add(seat1);
if (R1S10.getBackground().equals(Color.red) &&(IsSeatBooked().equals("true"))){
Component frame = null;
JOptionPane.showMessageDialog(frame, "Seat UnBooked");
seat1.setBooked("false");
seat1.setName("");
R1S10.setBackground(Color.yellow);
try {
reader();
writer();
//String booked = "true";
//Pass String booked into csv file
} catch (IOException ex) {
Logger.getLogger(SeatingPlan.class.getName()).log(Level.SEVERE, null, ex);
}
}
else{
Component frame = null;
String name = JOptionPane.showInputDialog(frame, "Please enter name of Customer booking");
if (name.isEmpty()) {
JOptionPane.showMessageDialog(frame, "No value entered");
} else if (name != null) {
seat1.setName(name);
seat1.setBooked("true");
R1S10.setBackground(Color.red);
JOptionPane.showMessageDialog(frame, "Your Booking has been placed");
try {
writer();
reader();
//String booked = "true";
//Pass String booked into csv file
} catch (IOException ex) {
Logger.getLogger(SeatingPlan.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
Followed by the screen below -
Outcome -
And when the button is pressed again -
I am using three methods in this SeatingPlan.java - writer(),reader() and IsSeatBooked().
SeatingPlan -
public class SeatingPlan extends javax.swing.JFrame {
/**
* Creates new form SeatingPlan
*/
String seatNo, name, bookedSeat;
FileWriter fileWriter = null;
List<Seat> seats = new ArrayList<Seat>();
//Seat Object Declaration
Seat seat1 = new Seat("R1S10","","false");
Seat seat2 = new Seat("R1S9", "", "false");
String fileName = "seat.csv";
writer -
public void writer() throws IOException {
//Delimiter used in CSV file
final String NEW_LINE_SEPARATOR = "\n", COMMA_DELIMITER = ",";
//CSV file header
final String FILE_HEADER = "seatID,name,booked";
//fileName = System.getProperty("user.home") + "/seat.csv";
try {
fileWriter = new FileWriter(fileName);
//Write the CSV file header
fileWriter.append(FILE_HEADER.toString());
//Add a new line separator after the header
fileWriter.append(NEW_LINE_SEPARATOR);
//Write a new student object list to the CSV file
for (Seat seat : seats) {
fileWriter.append(String.valueOf(seat.getSeatID()));
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(seat.getName());
fileWriter.append(COMMA_DELIMITER);
fileWriter.append(seat.isBooked());
fileWriter.append(NEW_LINE_SEPARATOR);
}
System.out.println("CSV file was created successfully !!!");
} catch (Exception e) {
System.out.println("Error in CsvFileWriter !!!");
e.printStackTrace();
} finally {
fileWriter.flush();
fileWriter.close();
}
}
reader -
public void reader() {
//Delimiter used in CSV file
final String COMMA_DELIMITER = ",";
//Student attributes index
final int SEAT_ID_IDX = 0;
final int SEAT_NAME_IDX = 1;
final int SEAT_BOOKED = 2;
//private static final int STUDENT_LNAME_IDX = 2;
BufferedReader fileReader = null;
try {
//Create a new list of student to be filled by CSV file data
List<Seat> seats = new ArrayList<>();
String line = "";
//Create the file reader
fileReader = new BufferedReader(new FileReader(fileName));
//Read the CSV file header to skip it
fileReader.readLine();
//Read the file line by line starting from the second line
while ((line = fileReader.readLine()) != null) {
//Get all tokens available in line
String[] tokens = line.split(COMMA_DELIMITER);
if (tokens.length > 0) {
//Create a new seat object and fill his data
Seat seat = new Seat(tokens[SEAT_ID_IDX],
tokens[SEAT_NAME_IDX], tokens[SEAT_BOOKED]);
seats.add(seat);
seatNo = tokens[SEAT_ID_IDX];
//System.out.println("Seat Number: " + seatNo);
bookedSeat = tokens[SEAT_BOOKED];
}
}
//Print the new student list
for (Seat seat : seats) {
System.out.println(seat.toString());
}
} catch (Exception e) {
System.out.println("Error in CsvFileReader !!!");
e.printStackTrace();
} finally {
try {
fileReader.close();
} catch (IOException e) {
System.out.println("Error while closing fileReader !!!");
e.printStackTrace();
}
}
}//end reader
SeatingPlan - This if where I have tried to have the arguments controlling the outcome but IsBooked is colliding when multiple seats are selected.
public SeatingPlan() throws IOException {
setVisible(true);
initComponents();
//reader();
ColourSectionGold();
ColourSectionBronze();
reader();
if(R1S10.getBackground().equals(Color.yellow) && (IsSeatBooked().equals("true"))){ R1S10.setBackground(Color.red);}
//if(R1S9.getBackground().equals(Color.yellow) && (IsSeatBooked().equals("true2"))){ R1S9.setBackground(Color.red);}
}
IsSeatBooked -
public String IsSeatBooked(){
return bookedSeat;
}//end IsSeatBooked
Im using the method above as my argument to see whether a seat is booked or not, but when a new seat is click it sets the whole value of 'bookedSeat' - which leaves the system not working correctly. I understand the code is not very efficient but is there any temporary fix for this problem, if I have explained it correctly.
Also I will include my class for Seat -
public class Seat {
private String seatID;
private String booked;
private String name;
private int price;
public Seat(String seatID,String name,String booked){
this.seatID = seatID;
this.booked = "";
this.name = name;
this.price = price;
}
public String getSeatID() {
return seatID;
}
public void setSeatID(String seatID) {
this.seatID = seatID;
}
public String isBooked() {
return booked;
}
public void setBooked(String booked) {
this.booked = booked;
}
public String getStatus(){
return booked;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setPrice() {
this.price = price;
}}//end class Seat
And a look at the CSV file that is created -
I wish to be able to click more than one button and save its state, Button 10 works fine at the moment, but as IsBooked only has one value at a time it clashes.
If you took the time to check this out, I appreciate it. Any constructive criticism is helpful and any ideas would be great!
Thanks,
Paddy.
Too much code to look at to see exactly what you are doing.
Instead of using your csv file, you could create a Properties file. The Propertiesfile will store the data in the form of:
key:data
So in your case the key would be the id: A1, A2... and the data would be the name of the person who booked the seat.
So the file would start out as empty. When you create the GUI you would create a loop that checks each id to see if an entry is found in the Properties field. If it is found then you display the seat as taken, otherwise it is empty.
Then whenever you want to book a seat you just use the setProperty(...) method.
The Properties class has load(...) and store(...) methods.
So the Properties class allows you to easily manage a flat file database with minimal effort.
Note, you would never have variable names like R1S10. That would requirement 100 different variables with if/else statements. Instead you would extend JButton and pass in the row and seat as parameters the button. Then in the ActionListener for the button you can access the row/seat information to built the ID used as the key for the properties file.
Edit:
Couldn't quite make the loop that checks if the ID is in the properties file.
If the property is null, the seath is empty.
import java.util.*;
public class Main
{
public static void main(String[] args)
{
Properties properties = new Properties();
properties.setProperty("A2", "Smith");
properties.setProperty("C3", "Jones");
String[] rows = { "A", "B", "C", "D" };
int seats = 4;
for (int row = 0; row < rows.length; row++)
{
for (int seat = 1; seat <= seats; seat++)
{
String key = rows[row] + seat;
String property = properties.getProperty( key );
System.out.println(key + " : " + property);
}
}
}
}
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 this code, that I'm trying to take the user input from the addEntry() method and write a method to save that to file.
public class GradeBook {
private String course;
private ArrayList<Person> students = new ArrayList<Person>();
private ArrayList<GradeBookEntry> entries = new ArrayList<GradeBookEntry>();
public GradeBook(String course){
this.course = course;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public void addStudent( Person student ){
students.add(student);
}
public void addEntry(){
System.out.println("Grade which student: ");
for (int i = 0; i < students.size(); i++) {
System.out.println(i + " " + students.get(i).getName());
}
Scanner reader = new Scanner(System.in);
int studentIndex = reader.nextInt();
reader.nextLine();
System.out.println("Enter the assessment name: ");
String assessmentName = reader.nextLine();
System.out.println("Homework (1) or exam (2): ");
int entryType = reader.nextInt();
reader.nextLine();
GradeBookEntry newEntry;
// TODO: create either a Homework or Exam entry
if( entryType == 1 ){
newEntry = new HomeworkEntry(assessmentName);
}
else {
newEntry = new ExamEntry(assessmentName);
}
// TODO: add getData method to the Homework and Exam
newEntry.getData();
newEntry.setStudent(students.get(studentIndex));
entries.add(newEntry);
}
This is the method below that I created but the text file doesnt have the correct data in it, I guess I somehow need the variables from the first method like "studentIndex" "entryType" etc., can you point me in the right direction?
public void writeFile(String fileName){
try {
FileWriter writer = new FileWriter(fileName);
for (int i=0; i<entries.size(); i++){
writer.write(students.get(i).toString());
}
writer.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Overriding toString of Person class should be the correct way to go about this.
*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 .