How to increment a number from a saved text file? - java

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

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

Is there a way to access the date added to an ArrayList in a different to change its data?

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

Error:Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:0

I get this error when running my code:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
at Module11_13_RealWorldProblem.main(Module11_13_RealWorldProblem.java:194)
I am not sure how to fix it. I have a text doc that it should read for the information, but its not running.
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
class User
{
private final String id;
private final String lstName;
private final String FstName;
private final String addressLine1;
String addressLine2;
private final String City;
private final String State;
private final long zip;
long zipPlus4;
private final double payAmount;
private final String payDate;
private final double payDue;
public User(String id,String lstName,String fstName,
String addressLine1,String addressLine2,String City,
String State,long zip,long zipPlus4,
String payDate,double payAmount,double payDue)
{
this.id=id;
this.lstName=lstName;
this.FstName=fstName;
this.addressLine1=addressLine1;
this.addressLine2=addressLine2;
this.City=City;
this.State=State;
this.zip=zip;
this.zipPlus4=zipPlus4;
this.payAmount=payAmount;
this.payDate=payDate;
this.payDue=payDue;
}
public void setAddLine2(String add){
this.addressLine2=add;}
public void setZipPlus4(long zip){
this.zipPlus4=zip;}
public long getZip()
{
return zip;
}
public double getPayAMount()
{
return payAmount;
}
public double getDueAMount()
{
return payDue;
}
public String getDate()
{
return payDate;
}
public String getaddressLine1()
{
return addressLine1;
}
public String getaddressLine2()
{
return addressLine2;
}
public String getCity()
{
return City;
}
public String getState()
{
return State;
}
public String getlstName()
{
return lstName;
}
public String getId()
{
return id;
}
public String getfstName()
{
return FstName;
}
public long getZipPlus4(){
return zipPlus4;}
}
public class Module11_13_RealWorldProblem {
public static void main(String[] args){
List<User> lst=new ArrayList<User>();
Scanner in=new Scanner(System.in);
File file = new File(args[0]);
if (!file.exists()) {
System.out.println(args[0] + " does not exist.");
return;
}
if (!(file.isFile() && file.canRead())) {
System.out.println(file.getName() + " cannot be read from.");
return;
}
try {
List<String> allLines = Files.readAllLines(Paths.get(args[0]));
for (String line : allLines) {
//System.out.println(line);
String[] str=line.split("\\^");
User user=new User(str[0],str[1],str[2],
str[3],"".equals(str[4])?"NoValue":str[4],str[5],str[6],
Long.valueOf(str[7]),"".equals(str[8])?Long.MAX_VALUE:Long.valueOf(str[8]),
str[9],Double.valueOf(str[10]),Double.valueOf(str[11]));
lst.add(user);
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Do opertauiosn,");
System.out.println("Do you want to output the report to the screen ('S'), to a file ('F') or both ('B')");
String ch=in.nextLine();
StringBuilder sb=new StringBuilder();
for (User user : lst) {
sb.append(user.getId()+"^"+user.getlstName()+","+user.getfstName()+"^"+user.getaddressLine1()
+"^"+("NoValue".equals(user.getaddressLine2())?"":user.getaddressLine2())+"^"+user.getCity()+"^"+user.getState()+"^"+user.getZip()+"^"+(
Long.MAX_VALUE==user.getZipPlus4()?"":user.getZipPlus4())
+"^"+user.getPayAMount()+"^"+user.getPayAMount()+"^"+user.getDueAMount());
sb.append("\n");
}
if("S".equalsIgnoreCase(ch))
{
System.out.println(sb.toString());
}
else if("F".equalsIgnoreCase(ch))
{
System.out.println("Enter output file name with full path");
String outputFilename=in.nextLine();
log(sb.toString(),outputFilename);
System.out.println("File successfully written");
}
else if("B".equalsIgnoreCase(ch))
{
System.out.println(sb.toString());
System.out.println("Enter output file name with full path");
String outputFilename=in.nextLine();
log(sb.toString(),outputFilename);
System.out.println("File successfully written");
}
}
public static void log(String message,String fName){
try {
PrintWriter out = new PrintWriter(new FileWriter(fName, true), true);
out.write(message);
out.close();
} catch (Exception e) {
System.out.print("There is something wrong in output file/file path..retry !");
}
}
}
When producing the report
Skip those fields that are not part of the report format
Rearrange those fields that are in a different order so they correspond to the report format
Add a prompt to the user "Do you want to output the report to the screen ('S'), to a file ('F') or both ('B')".
If the user enters 'S' your code should display the report to the screen as it currently does.
Whether the user enters an uppercase or lowercase letter should not matter. For example 'S' or 's' should not matter. In both cases, the user should display the data as described above.
If the user enters "F" (or "f"), then the app should
Prompt the user for the desired file name (including the file path)
Output the report to a file using the file name / path the user entered. This output should be in the exact same format as the report is-if sent to the screen except that it outputs the report to a file.
If the user enters "B" (or "b"), then the app should output the report to both the screen and output it to a file.
The Program expects a input from command line while running the program.
File file = new File(args[0]);
args being a empty array, throwing an indexOutOfBoundException.
Make sure while running the program you are passing the file name.

possible already open file error; halted

So, when I run this, I get no exceptions, but the execution halts. I entered a few lines of code to see where the hault is coming from. On initial execution, it creates a file in the path given in the Customer class. Once I do one of the actions, it doesn't let me go past the first debugging line. Ideas?
Heres the application:
package javaapplication18.pkg3;
import java.util.ArrayList;
import java.util.Scanner;
public class JavaApplication183 {
/**
* #param args the command line arguments
*/
static boolean keepGoing = true;
public static void main(String[] args) {
System.out.println("Welcome to the Customer Maintenance application");
//keepGoing = true;
Scanner sc = new Scanner(System.in);
while (keepGoing){
displayMenu();
String userChoice = getRequiredString("Enter a command: ", sc);
System.out.println("DEBUG LINE 1");
CustomerTextFile textFile = new CustomerTextFile();
System.out.println("DEBUG LINE 2");
performAction(userChoice, textFile);
System.out.println("DEBUG LINE 3");
}
// TODO code application logic here
}
public static void displayMenu() {
System.out.println();
System.out.println("COMMAND MENU");
System.out.println("list - List all customers");
System.out.println("add - Add a customer");
System.out.println("del - Delete a customer");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application");
System.out.println();
}
public static void performAction(String choice, CustomerTextFile textFile){
Scanner sc = new Scanner(System.in);
switch (choice.toLowerCase()) {
case "list":
//action
ArrayList<Customer> currentList = textFile.getCustomers();
for (Customer c : currentList) {
System.out.print(c.getEmail() + "\t");
System.out.print(c.getFirstName() + "\t");
System.out.println(c.getLastName());
}
break;
case "add":
String email = getRequiredString("Enter customer email address:", sc);
String firstName = getRequiredString("Enter first name:", sc);
String lastName = getRequiredString("Enter last name:", sc);
Customer c = new Customer(email, firstName, lastName);
textFile.addCustomer(c);
System.out.println(firstName + lastName + " was added to the database.");
break;
case "del":
String deleteUserByEmail = getRequiredString("Enter customer email to delete:", sc);
Customer delCustomer = textFile.getCustomer(deleteUserByEmail);
textFile.deleteCustomer(delCustomer);
break;
case "help":
//displayMenu();
break;
case "exit":
keepGoing = false;//exit();
break;
default:
System.out.println("You entereed something not in the list. Please try again.");
System.out.println();
}
}
public static boolean exit(){
System.out.println("Exit");
return false;
}
public static String getRequiredString(String prompt, Scanner sc) {
String s = "";
boolean isValid = false;
while (isValid == false) {
System.out.print(prompt);
s = sc.nextLine();
if (s.equals(""))
System.out.println("Error! This entry is required. Try again.");
else
isValid = true;
}
return s;
}
}
Here is the CustomerTextFile class:
package javaapplication18.pkg3;
import java.io.*;
import java.nio.file.*;
import java.util.ArrayList;
public class CustomerTextFile implements CustomerDAO{
private ArrayList<Customer> customers = null;
private Path customersPath = null;
private File customersFile = null;
public CustomerTextFile(){
customersPath = Paths.get("customers.txt");
customersFile = customersPath.toFile();
customers = this.getCustomers();
}
#Override
public Customer getCustomer(String emailAddress) {
for (Customer c : customers) {
if (c.getEmail().equals(emailAddress))
return c;
}
return null;
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public ArrayList<Customer> getCustomers() {
if (customers != null)
return customers;
customers = new ArrayList<>();
if (!Files.exists(customersPath)) {
try {
Files.createFile(customersPath);
}
catch (IOException e) {
return null;
}
}
if (Files.exists(customersPath)) {
try (BufferedReader in = new BufferedReader(new FileReader(customersFile))){
String line = in.readLine();
while(line != null) {
String[] columns = line.split("\t");
String email = columns[0];
String firstName = columns[1];
String lastName = columns[2];
Customer c = new Customer(email, firstName, lastName);
customers.add(c);
}
}
catch (IOException e) {
System.out.println(e);
return null;
}
}
return customers;
}
#Override
public boolean addCustomer(Customer c) {
customers.add(c);
return this.saveCustomers();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public boolean updateCustomer(Customer c) {
Customer oldCustomer = this.getCustomer(c.getEmail());
int i = customers.indexOf(oldCustomer);
customers.remove(i);
customers.add(i, c);
return this.saveCustomers();
//throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
public boolean deleteCustomer(Customer c) {
customers.remove(c);
return this.saveCustomers();
}
private boolean saveCustomers() {
try (PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter(customersFile)))){
for (Customer customer : customers) {
out.print(customer.getEmail() + "\t");
out.print(customer.getFirstName() + "\t");
out.println(customer.getLastName());
}
out.close();
return true;
}
catch (IOException e) {
return false;
}
}
}
Im not certain if the problem is in the application or if it is in the textfile class
run:
Welcome to the Customer Maintenance application
COMMAND MENU
list - List all customers
add - Add a customer
del - Delete a customer
help - Show this menu
exit - Exit this application
list
DEBUG LINE 1
Above was an example of the console output.
Why are you declaring a string inside the loop?
try this instead:
Scanner sc = new Scanner(System.in);
String userChoice;
do {
displayMenu();
userChoice = sc.nextLine(); //takes in the entire lien you type in
System.out.println("DEBUG LINE 1");
CustomerTextFile textFile = new CustomerTextFile();
System.out.println("DEBUG LINE 2");
performAction(userChoice, textFile);
System.out.println("DEBUG LINE 3");
} while(keepGoing);
Hope this helps

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!

Categories

Resources