I really just need a point in the right direction for this code. I do not understand how to accomplish what it is asking.
Modify the ProductMainApp class so it responds appropriately if the addProduct and deleteProduct mwthod in the ProductTextFile class returns a flase value.
Modify the ProductTextFile class so it writes exceptions to a tex file names errorLog.txt instead of printing them to the console. To do that, add a method named printToLogFile that accepts an IOException as an argument. This method should append two records to the log file: one that indicates the date and time the exception occured and one that contains information about the exception.
Modify the getProducts and saveProducts methods so they call the printToLogFile method when an error occurs.
Here is the PrintTextFile:
import java.util.*;
import java.io.*;
import java.nio.file.*;
public final class ProductTextFile implements ProductDAO
{
private ArrayList<Product> products = null;
private Path productsPath = null;
private File productsFile = null;
private final String FIELD_SEP = "\t";
public ProductTextFile()
{
productsPath = Paths.get("products.txt");
productsFile = productsPath.toFile();
products = this.getProducts();
}
public ArrayList<Product> getProducts()
{
// if the products file has already been read, don't read it again
if (products != null)
return products;
products = new ArrayList<>();
if (Files.exists(productsPath)) // prevent the FileNotFoundException
{
try
{
if (true)
{
// throw new IOException();
}
// open the input stream
BufferedReader in =
new BufferedReader(
new FileReader(productsFile));
// read all products stored in the file
// into the array list
String line = in.readLine();
while(line != null)
{
String[] columns = line.split(FIELD_SEP);
String code = columns[0];
String description = columns[1];
String price = columns[2];
Product p = new Product(
code, description, Double.parseDouble(price));
products.add(p);
line = in.readLine();
}
// close the input stream
in.close();
}
catch(IOException e)
{
//System.out.println(e);
return null;
}
}
return products;
}
public Product getProduct(String code)
{
for (Product p : products)
{
if (p.getCode().equals(code))
return p;
}
return null;
}
public boolean addProduct(Product p)
{
products.add(p);
return this.saveProducts();
}
public boolean deleteProduct(Product p)
{
products.remove(p);
return this.saveProducts();
}
public boolean updateProduct(Product newProduct)
{
// get the old product and remove it
Product oldProduct = this.getProduct(newProduct.getCode());
int i = products.indexOf(oldProduct);
products.remove(i);
// add the updated product
products.add(i, newProduct);
return this.saveProducts();
}
private boolean saveProducts()
{
try
{
// open the output stream
PrintWriter out = new PrintWriter(
new BufferedWriter(
new FileWriter(productsFile)));
// write all products in the array list
// to the file
for (Product p : products)
{
out.print(p.getCode() + FIELD_SEP);
out.print(p.getDescription() + FIELD_SEP);
out.println(p.getPrice());
}
// close the output stream
out.close();
}
catch(IOException e)
{
System.out.println(e);
return false;
}
return true;
}
}
Here is the ProductMainApp:
import java.util.Scanner;
import java.util.ArrayList;
public class ProductMaintApp implements ProductConstants
{
// declare two class variables
private static ProductDAO productDAO = null;
private static Scanner sc = null;
public static void main(String args[])
{
// display a welcome message
System.out.println("Welcome to the Product Maintenance application\n");
// set the class variables
productDAO = DAOFactory.getProductDAO();
sc = new Scanner(System.in);
// display the command menu
displayMenu();
// perform 1 or more actions
String action = "";
while (!action.equalsIgnoreCase("exit"))
{
// get the input from the user
action = Validator.getString(sc,
"Enter a command: ");
System.out.println();
if (action.equalsIgnoreCase("list"))
displayAllProducts();
else if (action.equalsIgnoreCase("add"))
{
addProduct();
}
else if (action.equalsIgnoreCase("del") || action.equalsIgnoreCase("delete"))
deleteProduct();
else if (action.equalsIgnoreCase("help") || action.equalsIgnoreCase("menu"))
displayMenu();
else if (action.equalsIgnoreCase("exit") || action.equalsIgnoreCase("quit"))
System.out.println("Bye.\n");
else
System.out.println("Error! Not a valid command.\n");
}
}
public static void displayMenu()
{
System.out.println("COMMAND MENU");
System.out.println("list - List all products");
System.out.println("add - Add a product");
System.out.println("del - Delete a product");
System.out.println("help - Show this menu");
System.out.println("exit - Exit this application\n");
}
public static void displayAllProducts()
{
System.out.println("PRODUCT LIST");
ArrayList<Product> products = productDAO.getProducts();
Product p = null;
StringBuilder sb = new StringBuilder();
if (productDAO.getProducts().equals(null))
{
System.out.println("Value Null");
System.exit(0);
}
for (int i = 0; i < products.size(); i++)
{
p = products.get(i);
sb.append(StringUtils.padWithSpaces(
p.getCode(), CODE_SIZE + 4));
sb.append(StringUtils.padWithSpaces(
p.getDescription(), DESCRIPTION_SIZE + 4));
sb.append(
p.getFormattedPrice());
sb.append("\n");
}
System.out.println(sb.toString());
}
public static void addProduct()
{
String code = Validator.getString(
sc, "Enter product code: ");
String description = Validator.getLine(
sc, "Enter product description: ");
double price = Validator.getDouble(
sc, "Enter price: ");
Product product = new Product();
product.setCode(code);
product.setDescription(description);
product.setPrice(price);
productDAO.addProduct(product);
System.out.println();
System.out.println(description
+ " has been added.\n");
}
public static void deleteProduct()
{
String code = Validator.getString(sc,
"Enter product code to delete: ");
Product p = productDAO.getProduct(code);
System.out.println();
if (p != null)
{
productDAO.deleteProduct(p);
System.out.println(p.getDescription()
+ " has been deleted.\n");
}
else
{
System.out.println("No product matches that code.\n");
}
}
}
You can use Exception.printStackTrace (stream) where stream is a outputstream to a file.
http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)
Related
Either my save_product function in my Repository.java class doesn't save correctly into the map product_repository or, maybe it does save, but I'm not outputting it correctly in my find_product function in my Repository.java class. I think I'm using the correct function to search for the value in the map, .get
I experimented with product_repository.keySet().iterator().forEachRemaining(System.out::println); but that's the first time I ever used that... also please forgive how I insert the keyinto the map product_repository in the create_new_product function in the Controller.java class. I'm new to java ...
Main.java
package com.company;
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
Product.java
package com.company;
public class Product {
private String product_name;
private String product_brand;
private int product_cost;
private int product_count;
private boolean product_availability;
public Product() {
}
public Product(String product_name, String product_brand,
int product_cost, int product_count, boolean product_availability) {
this.product_name = product_name;
this.product_brand = product_brand;
this.product_cost = product_cost;
this.product_count = product_count;
this.product_availability = product_availability;
}
public String getProduct_name() {
return product_name;
}
public void setProduct_name(String product_name) {
this.product_name = product_name;
}
public String getProduct_brand() {
return product_brand;
}
public void setProduct_brand(String product_brand) {
this.product_brand = product_brand;
}
public int getProduct_cost() {
return product_cost;
}
public void setProduct_cost(int product_cost) {
this.product_cost = product_cost;
}
public int getProduct_count() {
return product_count;
}
public void setProduct_count(int product_count) {
this.product_count = product_count;
}
public boolean isProduct_availability() {
return product_availability;
}
public void setProduct_availability(boolean product_availability) {
this.product_availability = product_availability;
}
}
Controller.java
package com.company;
import java.util.Scanner;
public class Controller {
private static Long key;
public static void create_new_product(){
Repository repository = new Repository();
//Supplier supplier = new Supplier();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
key = 0L;
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
key++;
repository.save_product(key, product);
}
public void search_product(){
Repository repository = new Repository();
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
repository.find_product(id);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
repository.find_product(name);
try{
if (product.getProduct_count() > 0){
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
}
else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
Repository.java
package com.company;
import java.util.HashMap;
import java.util.Map;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap){
try{
if (product_repository.containsValue(newProductMap)) {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
else {
product_repository.put(key, newProductMap);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public void find_product(Long key){
try {
if (product_repository.containsKey(key)) {
System.out.println(product_repository.get(key));
}
else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
// Overload
public void find_product(String name) {
try {
if (product_repository.containsValue(name)) {
System.out.println(product_repository.get(name));
product_repository.keySet().iterator().forEachRemaining(System.out::println);
}
else {
System.out.println("No matches were found for product name: " + name);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
}
You have to make Repository repository a field of your Controller class. You are currently throwing the repositories away after your methods create_new_product and search_product have executed. Therefore you need to remove the first line of each of these methods.
Another problem is inside your find_product(String name) method where your call product_repository.get(name) but name is a String and the get method expects an ID, i.e. a Long so this call will always return null.
As it was pointed out before the repository has to be made global. However, the entire code is a bit messy. You are searching for a product id but the id is not shown to you. It is like searching for database records but the ids are autogenerated. Good luck with that. So I would suggest to allow this program to enter the id as well. It makes much more sense if you want to search for the id.
Otherwise, if you are interested in only the value, id can be taken out.
Below you can find the modified code that works for all the methods.
//main stays the same
public class Main {
public static void main(String[] args) {
// write your code here
Controller controller = new Controller();
controller.create_new_product();
controller.search_product();
}
}
//controller is a bit changed. Added global repository and improved the search.
import java.util.Collection;
import java.util.Scanner;
public class Controller {
private static Long key;
Repository repository = new Repository();
public void create_new_product() {
Product product = new Product();
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("********************NEW PRODUCT CREATION PAGE********************");
System.out.println("*****************************************************************");
System.out.println("Enter product id: ");
long id = Long.parseLong(scanner.nextLine());
product.setProductId(id);
System.out.println("Enter product name: ");
String name = scanner.nextLine();
product.setProduct_name(name);
System.out.println("Enter product brand: ");
String brand = scanner.nextLine();
product.setProduct_brand(brand);
System.out.println("Enter product cost: ");
int cost = scanner.nextInt();
product.setProduct_cost(cost);
System.out.println("Enter amount of products in stock: ");
int amount = scanner.nextInt();
product.setProduct_count(amount);
repository.save_product(id, product);
}
public void search_product() {
Scanner scanner = new Scanner(System.in);
System.out.println("*****************************************************************");
System.out.println("*************************FIND PRODUCT PAGE***********************");
System.out.println("*****************************************************************");
// TO DO: Choices or if/else blocks not executing properly
System.out.println("\nSearch by ID or name?\nPress '1' for ID. Press '2' for name: ");
String choice = scanner.next();
if (choice.equals("1")) {
System.out.println("Enter product id: ");
Long id = scanner.nextLong();
Product product = repository.find_product(id);
try {
if (product.getProduct_count() > 0) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} catch (Exception e) {
System.out.println(product.getProduct_name() + " are out of stock.");
}
} else if (choice.equals("2")) {
System.out.println("Enter product name: ");
String name = scanner.next();
Collection<Product> products = repository.find_products(name);
if (products.size() > 0) {
for (Product product : products) {
System.out.println(product.getProduct_name() + " are in stock!");
}
} else {
System.out.println(" out of stock.");
}
} else {
System.out.println("Error. We apologize for the inconvenience.");
}
}
}
//Added a new field to the Repository so you can also search by key.
import java.util.*;
public class Repository {
private Map<Long, Product> product_repository = new HashMap<Long, Product>();
// TO DO: Implement while loops so program doesn't exit at the first error
public void save_product(Long key, Product newProductMap) {
try {
if (!product_repository.containsKey(key)) {
product_repository.put(key, newProductMap);
} else {
System.out.println("This product is already in the system." +
"\nFor safety reasons, we cannot add the same product twice.");
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
}
public Product find_product(final Long key) {
try {
if (product_repository.containsKey(key)) {
System.out.println("Found product: " + product_repository.get(key).getProduct_name());
return product_repository.get(key);
} else {
System.out.println("No matches were found for product id: " + key);
}
} catch (Exception e) {
System.out.println("System error. Consult the database administrator.");
}
return null;
}
// Overload
public Collection<Product> find_products(final String name) {
Collection<Product> values = new ArrayList<>();
for (Map.Entry<Long, Product> productEntry : product_repository.entrySet()) {
if (productEntry.getValue().getProduct_name().equals(name)) {
System.out.println("matches were found for product name: " + name);
values.add(productEntry.getValue());
}
}
return values;
}
}
so I am doing this assignment and after finishing it one part of the Code isn't executing properly.
Warehouse
class Warehouse {
private final Merchandise[] merchandise;
Warehouse(Merchandise[] merchandise) {
this.merchandise = merchandise;
}
public static Warehouse fromCsv(String file) {
In.open(file);
String material = In.readFile();
In.close();
String lines[] = material.split("\n");
Merchandise[] merchandise = new Merchandise[lines.length];
for(int i=0; i<merchandise.length; i++) {
String[] parts = lines[i].split(",");
Article article = null;
if(parts[0].equals("instrument")) {
article = new Instrument(parts[1],Double.parseDouble(parts[2]),parts[3],Integer.parseInt(parts[4]));
}else{
article = new Accessory(parts[1],Double.parseDouble(parts[2]),parts[3],parts[4]);
}
merchandise[i] = new Merchandise(article,Integer.parseInt(parts[5]));
}
return new Warehouse(merchandise);
}
public Merchandise[] getMerchandise() {
return merchandise.clone();
}
public Merchandise findMerchandise(String name) {
Merchandise found = null;
for(Merchandise the : merchandise) {
if(the.getArticle().getName().equals(name)) {
found = the;
break;
}
}
return found;
}
}
Shop
class Shop {
private final Warehouse warehouse;
Shop(Warehouse warehouse){
this.warehouse = warehouse;
}
public void printCatalog() {
Out.println();
Out.formatln("%-30s%20s%10s", "Name" , "Price","Quantity");
String format = "%-30s%20.2f%10d";
for(Merchandise the : warehouse.getMerchandise()) {
Out.formatln(format,the.getArticle().getName(),the.getArticle().getPrice(),the.getQuantity());
}
}
public void printProductDescription(String name){
Merchandise merchandise = warehouse.findMerchandise(name);
Out.println();
if(merchandise != null) {
Out.println(merchandise);
}else {
Out.println("The article does not exist");
Out.println();
}
}
}
Main
class Main {
public static void main(String[] args) {
Warehouse warehouse = Warehouse.fromCsv("warehouse.csv");
Shop shop = new Shop(warehouse);
while(true) {
Out.println("Pianos & more");
Out.println("0. Print Catalogue");
Out.println("1. Search Article");
Out.println();
Out.print("Selection:");
int selection = In.readInt();
In.read();
switch(selection) {
case 0:
shop.printCatalog();
break;
case 1:
Out.print("Article name:");
String name = In.readLine();
shop.printProductDescription(name);
break;
default:
Out.println("Invalid selection");
}
}
}
}
So the part where I print out the catalog is working fine, but when I try to search an article it takes the Article name, and just prints out "article doesn't exist" although it should. Any help on what I'm doing wrong?
I have created three methods readLong, readInt and readDouble that basically does the same thing. Only difference is the method called by a scanner. How can I reduce duplicate code by turning them all to one method?
public long readLong(String description)
{
System.out.println(description);
long nrToReturn = 0;
boolean acceptedValue = false;
do {
System.out.println();
System.out.print("Choose one: ");
try
{
nrToReturn = consoleScanner.nextLong(); //Only line thats different except return value
acceptedValue = true;
}catch(Exception e)
{
acceptedValue = false;
consoleScanner.nextLine();
}
}while (!acceptedValue);
consoleScanner.nextLine();
return nrToReturn;
}
Here we go with one idea:
import java.util.Scanner;
public class ScannerTest {
private Scanner consoleScanner;
public ScannerTest() {
consoleScanner = new Scanner(System.in);
}
#SuppressWarnings("unchecked")
private <T extends Number> T readType(String description, Class<T> desiredType) {
System.out.println(description);
Number result = null;
while (result == null) {
System.out.println();
System.out.print("Choose one: ");
try {
if (Integer.class.equals(desiredType)) {
result = new Integer(consoleScanner.nextInt());
} else if (Long.class.equals(desiredType)) {
result = new Long(consoleScanner.nextLong());
}
} catch(Exception e) {
consoleScanner.nextLine();
}
}
consoleScanner.nextLine();
return (T) result;
}
public long readLong(String description) {
return this.readType(description, Long.class);
}
public int readInt(String description) {
return this.readType(description, Integer.class);
}
public static void main(String[] args) {
ScannerTest t = new ScannerTest();
t.readLong("Reading a long value...");
t.readInt("Reading an integer value...");
}
}
Update, following #Michu93 idea of a single transparent method:
import java.util.Scanner;
public class ScannerTest {
private Scanner consoleScanner;
public ScannerTest() {
consoleScanner = new Scanner(System.in);
}
#SuppressWarnings("unchecked")
public <T extends Number> T readNumber(String description) {
System.out.println(description);
Number result = null;
while (result == null) {
System.out.print("\nChoose one: ");
String textRead = consoleScanner.next();
try {
result = new Integer(textRead);
} catch(Exception e1) {
try {
result = new Long(textRead);
} catch (Exception e2) {
try {
result = new Double(textRead);
} catch (Exception e3) {
}
}
}
consoleScanner.nextLine();
}
return (T) result;
}
public static void main(String[] args) {
ScannerTest t = new ScannerTest();
for (int i = 0; i < 3; i++) {
Number input = t.readNumber(i + ": Reading int, long or double...");
System.out.println("Input class: " + input.getClass().getCanonicalName());
System.out.println("Input value: " + input);
}
}
}
I have written a Java code which I need to be written in Map Reduce.
I am relatively new to Map Reduce concepts.
As an input, I have a file containing multiple columns which are Pipe delimited.
Based on certain criteria which are given in my if condition of my code, I need to link the Row-Id's from the file.
for Example:
rowid|rollno|sbjctcode|subjct|dt_of_exam......|marks
2|1000|0101|PHY|02072015......|-060
9|1000|0101|PHY|02072015......|060
Desired Output:
2[9]
so that, I can get to know where is the error in the file, or for a case multiple entries etc.
Here's my Java Code:
import java.io.*;
import java.util.*;
public class MRCode {
public static void main(String[] args) {
BufferedReader in = null;
BufferedWriter out = null;
String in_line;
String PrevRollNo = "150";
ArrayList<Transaction> PCMList = new ArrayList<Transaction>();
ArrayList<Transaction> AdditionalList = new ArrayList<Transaction>();
ArrayList<Transaction> OtherList = new ArrayList<Transaction>();
try {
in = new BufferedReader(new FileReader(
"C:\\Users\\Desktop\\data.txt"));
File out_file = new File("C:\\Users\\Desktop\\op.txt");
if (!out_file.exists()) {
out_file.createNewFile();
}
FileWriter fw = new FileWriter(out_file);
out = new BufferedWriter(fw);
while ((in_line = in.readLine()) != null) {
Transaction transact = new Transaction(in_line);
if (transact.rollNo.equals(PrevRollNo)) {
if (transact.subjctCode.equals("PHY")
|| transact.subjctCode.equals("CHEM")
|| transact.subjctCode.equals("MATH")
&& transact.dt_of_exam == PrevDate) {
PCMList.add(transact);
break;
} else {
OtherList.add(transact);
}
if (transact.subjctCode.equals("0101")) {
Iterator<Transaction> pcm;
pcm = PCMList.iterator();
while (pcm.hasNext()) {
Transaction pcmtxn = pcm.next();
if (pcmtxn.subjctCode.equals("0102")
&& pcmtxn.dt_of_exam == transact.dt_of_exam
&& pcmtxn.subjct.equals(transact.subjct)
&& pcmtxn.marks == Math.abs(transact.marks)) {
pcmtxn.tgtfound = true;
transact.srcfound = true;
System.out.println(pcmtxn.row_id + "["
+ transact.row_id + "]");
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
static class Transaction {
public String rollNo, subjctCode, subjct, l1, l2;
public int row_id, dt_of_exam, dt_of_chking;
public double marks;
public boolean srcfound, tgtfound;
public Transaction(String in_line) {
String[] SplitData = in_line.split("\\|");
row_id = Integer.parseInt(SplitData[0]);
rollNo = SplitData[1];
subjctCode = SplitData[4];
subjct = SplitData[5];
l1 = SplitData[7];
l2 = SplitData[8];
dt_of_exam = Integer.parseInt(SplitData[2]);
dt_of_chking = Integer.parseInt(SplitData[3]);
marks = Double.parseDouble(SplitData[11]);
srcfound = false;
tgtfound = false;
}
}
}
Please help me with your thoughts on how can use Array List in my mapper class.
or how can I write this code better in Map Reduce.
Note: This is just a snapshot.
Do share your views.
I have created a simple program that takes a title and a note which you enter then you have a choice to export the notes to txt file using BufferedWriter however because each note is a object which is stored in a ArrayList when storing them I iterate through a for enhanced loop it keeps duplicating each note as I iterate through all the object.
Note Class
import java.util.*;
public class Notes
{
private String notes;
private String titleOfNotes;
Scanner input = new Scanner(System.in);
public Notes()
{
titleOfNote(input);
takeNotes(input);
}
public void takeNotes(Scanner x)
{
System.out.println("Please Enter Your Note");
notes = x.nextLine();
}
public void titleOfNote(Scanner y)
{
System.out.println("Please Enter Title");
titleOfNotes = y.nextLine();
}
public String toString()
{
return "Title: " + titleOfNotes + "\t" + notes;
}
}
App Class //Does mostof the Work
import java.util.*;
import java.io.*;
public class App
{
private int exit = 0;
private int createANote;
private int displayTheNotes;
private int inputFromUser;
public boolean haveFileBeenWritten = true;
File file = new File("Notes.txt");
Scanner input = new Scanner(System.in);
ArrayList<Notes> arrayOfNotes = new ArrayList<Notes>();
public void makeNoteObject()
{
arrayOfNotes.add(new Notes());
}
public void displayAllTheNote(ArrayList<Notes> n)
{
for(Notes singleObjectOfNote : n)
{
System.out.println(singleObjectOfNote);
}
}
public void programUI(){
while(exit != 1)
{
System.out.println("1. Create A Note");
System.out.println("2. Display The Notes");
System.out.println("3. Exit");
System.out.println("4. Export to text file");
System.out.println("Enter Your Operation");
inputFromUser = input.nextInt();
if(inputFromUser == 1)
{
makeNoteObject();
}
else if(inputFromUser == 2)
{
displayAllTheNote(arrayOfNotes);
}
else if(inputFromUser == 3)
{
System.out.println("Exited");
exit = 1;
}
else if(inputFromUser == 4)
{
makeATxtFileFromNotes(arrayOfNotes);
System.out.println("Textfile created filename: " + file.toString());
}
else
{
System.out.println("You Select A Invalid Command");
}
}
}
public void makeATxtFileFromNotes(ArrayList<Notes> x)
{
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
{
//Problem here!
for(Notes singleObjectOfNotes : x)
{
bw.write(singleObjectOfNotes.toString());
bw.newLine();
}
}catch(IOException e)
{
System.out.println("Cant Write File: " + file.toString());
haveFileBeenWritten = false;
}
}
public App()
{
programUI();
}
public static void main(String[]args)
{
App objectOfApp = new App();
}
}
I am new to Java so my code my not be the best!
If your problem is that you only need to see current list's Notes excluding the previous', it's because of this line:
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file,haveFileBeenWritten)))
By default, haveFileBeenWritten is true so based on the FileWriter API it will APPEND on the existing file Notes.txt so if you don't want that, change it to false.
Parameters:
file - a File object to write to
append - if true, then bytes will be
written to the end of the file rather than the beginning
EDIT: To access List<> elements, use get().
Example:
int size = myList.size();
for (int i = 0 ; i < size ; i++) {
//...
Notes note = myList.get(i);
//...
}