Java getShopItem() and getShopUser methods - java

Hi Guys I am trying to write a method, getShopItem(), for the Shop class, that will return a pointer to a ShopItem object stored in itemsList when given the item's itemCode value, below is my attempt at coding which has been unsucessful and will not compile:
public shop item.getshopitem(shopItem)
{
return this.shopitem
}
Shop Class:
public class Shop
{
private ArrayList<Shop> shopCollection;
private ArrayList<ShopUser> usersList;
private ArrayList<Tool> toolsList;
private int toolCount;
private String toolName;
private int power;
private int timesBorrowed;
private boolean rechargeable;
private int itemCode;
private int cost;
private double weight;
private boolean onLoan;
private JFrame myFrame;
private FileDialog fileDialogBox;
private int mode;
public void ReadToolData (String data) throws FileNotFoundException,NoSuchElementException
{
// public void FileDialogBox() throws FileNotFoundException
{
if ( userSelectMode() ) // LOAD or SAVE if successful
{
String path = "E:/LEWIS BC 2/java project/project 1 part 3/items_all.txt"; // start browsing in root on drive E:
// String path = "E:/LEWIS BC 2/java project/project 1 part 3/userData.txt"; // start browsing in root on drive E:
setUpFileDialog(path);
fileDialogBox.setVisible(true);
}
else
{
String message = "No option selected, aborting";
String title = "Error";
JOptionPane.showMessageDialog(myFrame, message, title,
JOptionPane.WARNING_MESSAGE);
return; // or System.exit(1)
}
// see what the user has selected
String fileName = fileDialogBox.getFile();
if ( fileName==null )
{
String message = "Selection cancelled by user, aborting";
String title = "Error";
JOptionPane.showMessageDialog(myFrame, message, title,
JOptionPane.WARNING_MESSAGE);
return; // or System.exit(2)
}
String directoryPath = fileDialogBox.getDirectory();
String message = "File selected: " + fileName + "\nFolder: " + directoryPath;
JOptionPane.showMessageDialog(myFrame, message, "File Selected",
JOptionPane.INFORMATION_MESSAGE);
// now create a File object
File fileObject = new File(directoryPath, fileName);
// note that this does NOT create an actual file -- it simply
// creates a reference, or a "handle", for a file
// normally would now do something useful with the File object !!
// -- let's check if the file exists and, if so, when it was last modified
if ( fileObject.exists() )
{
Date whenModified = new Date(fileObject.lastModified());
DateFormat df = DateFormat.getDateTimeInstance();
message = "Time file was last modified: " + df.format(whenModified);
}
else
message = "File " + fileObject.getAbsolutePath() + " does not exist";
JOptionPane.showMessageDialog(myFrame, message, "Do Something Useful",
JOptionPane.INFORMATION_MESSAGE);
}
try
{ // The name of the file which we will read from
String filename = "items_all.txt";
// Prepare to read from the file, using a Scanner object
File file = new File(filename);
Scanner in = new Scanner(file);
ArrayList<Tool> shops = new ArrayList<Tool>();
// Read each line until end of file is reached
while (in.hasNextLine())
{
// Read an entire line, which contains all the details for 1 account
String line = in.nextLine();
// Make a Scanner object to break up this line into parts
Scanner lineBreaker = new Scanner(line);
// 1st part is the toolCount
try
{
// need to put checks for empty line & comments
int toolCount = lineBreaker.nextInt();
// 2nd part is the toolName
String toolName = lineBreaker.next();
// 3rd part is the amount of money or the Cost...
int cost = lineBreaker.nextInt();
int total = lineBreaker.nextInt();
}
catch (InputMismatchException e)
{
System.out.println("File not found1.");
}
catch (NoSuchElementException e)
{
System.out.println("File not found2");
}
}
}
catch (FileNotFoundException e)
{
System.out.println("File not found");
} // Make an ArrayList to store all the
// Return the ArrayList
// return shops;
}
public static void main(String[] args)
{
String test = "245.34,2456 345.2,34.12,23456 23,4";
Scanner input = new Scanner(test);
input.useDelimiter(",");
while (input.hasNextDouble())
{
System.out.println(input.nextDouble());
}
System.out.println("I get to the end");
}
/**
* Default Constructor for Testing
*/
public void extractTokens(Scanner scanner ) throws IOException, FileNotFoundException
{
//extracts tokens from the text file
File text = new File("E:/LEWIS BC 2/java project/project 1 part 3/items_all.txt");
String toolName = scanner.next();
String itemCode = scanner.next();
String power = scanner.next();
String timesBorrowed = scanner.next();
String onLoan = scanner.next();
String cost = scanner.next();
String weight = scanner.next();
extractTokens(scanner);
// System.out.println(parts.get(1)); // "en"
}
/**
* Creates a collection of tools to be stored in a tool list
*/
public Shop(String toolName, int power,int timesborrowed,boolean rechargeable,int itemCode,int cost,double weight,int toolcount,boolean onLoan)
{
toolsList = new ArrayList<Tool>();
toolName = new String();
power = 0;
timesborrowed = 0;
rechargeable = true;
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
onLoan = true;
}
/**
* Default Constructor for Testing
*/
public Shop()
{
// initialise instance variables
toolName = "Spanner";
itemCode = 001;
timesBorrowed = 0;
power = 0;
onLoan = true;
rechargeable = true;
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
}
//
// /**
// * Creates a collection of tools to be stored in a tool list
// */
// public Shop() {
// this.toolsList = new ArrayList<Tool>();
// this.toolName = toolName;
// this.power = power;
// this.timesborrowed = timesborrowed;
//
//
// }
//
// /**
// * Default Constructor for Testing
// */
// public Shop(){
// // Call the previous defined constructor
//
// }
/**
* Reads ElectronicToolData data from a text file
*
* #param <code>fileName</code> a <code>String</code>, the name of the
* text file in which the data is stored.
*
* #throws FileNotFoundException
*/
//
// while (there are more lines in the data file )
// {
// lineOfText = next line from scanner
// if( line starts with // )
// { // ignore }
// else if( line is blank )
// { // ignore }
// else
// { code to deal with a line of ElectricTool data }
// }
private boolean userSelectMode()
{
String[] options = {"LOAD", "SAVE"};
String instr = "Select LOAD for read access, SAVE for write access";
String title = "Select Mode";
int button = JOptionPane.showOptionDialog(myFrame, instr, title,
JOptionPane.DEFAULT_OPTION,
JOptionPane.QUESTION_MESSAGE,
null, options, null);
boolean success;
if ( button==0 )
{
mode = FileDialog.LOAD;
success = true;
}
else if ( button==1 )
{
mode = FileDialog.SAVE;
success = true;
}
else
success = false;
return success;
}
private void setUpFileDialog(String path)
{
String fileDialogTitle = null;
if ( mode == FileDialog.LOAD )
fileDialogTitle = "Open";
else if ( mode == FileDialog.SAVE)
fileDialogTitle ="Save As";
else
{
// defensive programming -- this should never happen !
System.out.println("*** Unexpected Error -- Aborting ***");
System.exit(1);
}
fileDialogBox = new FileDialog(myFrame, fileDialogTitle, mode);
fileDialogBox.setDirectory(path); // start browsing in folder
// corresponding to path
}
/**
* Creates a tool collection and populates it using data from a text file
*/
public Shop(String fileName) throws FileNotFoundException
{
this();
ReadToolData(fileName);
}
/**
* Adds a tool to the collection
*
* #param <code>tool</code> an <code>Tool</code> object, the tool to be added
*/
public void storeTool(Tool tool)
{
toolsList.add(tool);
}
/**
* Shows a tool by printing it's details. This includes
* it's position in the collection.
*
* #param <code>listPosition</code> the position of the animal
*/
public void showTool(int listPosition)
{
Tool tool;
if( listPosition < toolsList.size() )
{
tool = toolsList.get(listPosition);
System.out.println("Position " + listPosition + ": " + tool);
}
}
/**
* Returns how many tools are stored in the collection
*
* #return the number of tools in the collection
*/
public int numberOfToolls()
{
return toolsList.size();
}
/**
* Displays all the tools in the collection
*
*/
public void showAllTools()
{
System.out.println("Shop");
System.out.println("===");
int listPosition = 0;
while( listPosition<toolsList.size() ) //for each loop
{
showTool(listPosition);
listPosition++;
}
System.out.println(listPosition + " tools shown" ); // display number of tools shown
}
public void printShopiteDetails()
{
// The name of the file to open.
String fileName = "items_all.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
/**
* Adds a shop item to the shop.
*
* #param <code>shop</code> an <code>Shop</code> object, the Shop item can be added to the shop.
*/
public void storeShopitem(Shop shop)
{
shopCollection.add(shop);
}
/**
* Adds a shop user to the shop.
*
* #param <code>shop</code> an <code>Shop</code> object, the new Shop user can be added to the shop.
*/
public void storeShopUser(ShopUser shopUser)
{
usersList.add(shopUser);
}
/**
* Accessor method processhireRequest
*
* #return shopuser and shopitem object's
*/
public void processHireRequest(ShopItem shopItem, ShopUser shopUser)
{
this.itemCode = itemCode;
}
/**
* Accessor method processhireRequest
*
* #return shopuser and shopitem object's
*/
public void processReturnRequest(ShopItem shopItem, ShopUser shopUser)
{
this.itemCode = itemCode;
}
}
ShopItem class:
public abstract class ShopItem
{
private ArrayList<Tool> toolsList;
Shop shop;
private int toolCount;
private String toolName;
private int power;
private int timesBorrowed;
private boolean rechargeable;
private int itemCode;
private int cost;
private double weight;
private boolean onLoan;
private static JFrame myFrame;
private String Tool;
private String ElectricTool;
private String HandTool;
private String Perishable;
private String Workwear;
private String ShopUserID;
public void ReadToolData (String data) throws FileNotFoundException,NoSuchElementException
{
// shows the directory of the text file
File file = new File("E:/LEWIS BC 2/java project/project 1 part 3/ElectricToolData.txt");
Scanner S = new Scanner (file);
// prints out the data
System.out.println();
// prints out the
System.out.println();
S.nextLine();
S.nextLine();
S.nextLine();
S.nextLine();
S.nextInt ();
}
/**
* Creates a collection of tools to be stored in a tool list
*/
public ShopItem(String toolName, int power,int timesborrowed,boolean rechargeable,int itemCode,int cost,double weight,int toolcount,boolean onLoan,boolean ShopUserID)
{
toolsList = new ArrayList<Tool>();
rechargeable = true;
power = 0;
timesborrowed = 0;
// ShopUserID = new String();
toolName = new String();
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
onLoan = true;
// ShopUserID = null;
}
/**
* Default Constructor for Testing
*/
public ShopItem()
{
// initialise instance variables
rechargeable = true;
power = 0;
timesBorrowed = 0;
ShopUserID = "SU002171";
toolName = "Spanner";
itemCode = 001;
cost = 100;
weight = 0.0;
toolCount = 0;
onLoan = true;
}
/**
* Reads ElectronicToolData data from a text file
*
* #param <code>fileName</code> a <code>String</code>, the name of the
* text file in which the data is stored.
*
* #throws FileNotFoundException
*/
public void readData(String fileName) throws FileNotFoundException
{
//
// while (there are more lines in the data file )
// {
// lineOfText = next line from scanner
// if( line starts with // )
// { // ignore }
// else if( line is blank )
// { // ignore }
// else
// { code to deal with a line of ElectricTool data }
// }
myFrame = new JFrame("Testing FileDialog Box");
myFrame.setBounds(200, 200, 800, 500);
myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
myFrame.setVisible(true);
{
FileDialog fileBox = new FileDialog(myFrame,
"Open", FileDialog.LOAD);
fileBox.setVisible(true);
}
{
File dataFile = new File(fileName);
Scanner scanner = new Scanner(dataFile);
while( scanner.hasNext() )
{
String info = scanner.nextLine();
System.out.println(info);
}
scanner.close();
}
}
/**
* Default Constructor for Testing
*/
public void extractTokens(Scanner scanner) throws IOException, FileNotFoundException
{
// extracts tokens from the scanner
File text = new File("E:/LEWIS BC 2/java project/java project part 3/step_5_data.txt");
String ToolName = scanner.next();
int itemCode = scanner.nextInt();
int cost = scanner.nextInt();
int weight = scanner.nextInt();
int timesBorrowed = scanner.nextInt();
boolean rechargeable = scanner.nextBoolean();
boolean onLoan = scanner.nextBoolean();
String ShopUserID = scanner.next();
extractTokens(scanner);
// System.out.println(parts.get(1)); // "en"
}
/**
* Creates a tool collection and populates it using data from a text file
*/
public ShopItem(String fileName) throws FileNotFoundException
{
this();
ReadToolData(fileName);
}
/**
* Adds a tool to the collection
*
* #param <code>tool</code> an <code>Tool</code> object, the tool to be added
*/
public void storeTool(Tool tool)
{
toolsList.add(tool);
}
/**
* Shows a tool by printing it's details. This includes
* it's position in the collection.
*
* #param <code>listPosition</code> the position of the animal
*/
public void showTool(int listPosition)
{
Tool tool;
if( listPosition < toolsList.size() )
{
tool = toolsList.get(listPosition);
System.out.println("Position " + listPosition + ": " + tool);
}
}
/**
* Returns how many tools are stored in the collection
*
* #return the number of tools in the collection
*/
public int numberOfToolls()
{
return toolsList.size();
}
/**
* Displays all the tools in the collection
*
*/
public void showAllTools()
{
System.out.println("Shop");
System.out.println("===");
int listPosition = 0;
while( listPosition<toolsList.size() ) //for each loop
{
showTool(listPosition);
listPosition++;
}
System.out.println(listPosition + " tools shown" ); // display number of tools shown
}
public void printAllDetails()
{
// The name of the file to open.
String fileName = "ElectricToolDataNew.txt";
// This will reference one line at a time
String line = null;
try {
// FileReader reads text files in the default encoding.
FileReader fileReader =
new FileReader(fileName);
// Always wrap FileReader in BufferedReader.
BufferedReader bufferedReader =
new BufferedReader(fileReader);
while((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
// Always close files.
bufferedReader.close();
}
catch(FileNotFoundException ex) {
System.out.println(
"Unable to open file '" +
fileName + "'");
}
catch(IOException ex) {
System.out.println(
"Error reading file '"
+ fileName + "'");
// Or we could just do this:
// ex.printStackTrace();
}
}
}
is this above code correct and should it work??
any answers or help would be greatly appreciated.

public shop item.getshopitem(shopItem)
This isn't valid Java. You dont need to prepend the function.
public ShopItem getshopitem(int shopItem)

I think the method you are trying to write is
public ShopItem getShopItem(int shopItem)
{
return this.shopItem;
}
Although, in the actual method implementation, you will want to search your list of ShopItems for the given item code.
If you are going to be storing item codes that correspond to ShopItems, I suggest using a HashMap with item codes as the keys and ShopItems as the values.

Related

TreeMap with (String,ArrayList<String,Int>)

I am trying to read an input file. Each value of the input file is inserted into the TreeMap as
If word is not existing: Insert the word to the treemap and associate the word with an ArrayList(docId, Count).
If the Word is present in the TreeMap, then check if the current DocID matches within the ArrayList and then increase the count.
THe
For the ArrayList, I created another class as below:
public class CountPerDocument
{
private final String documentId;
private final int count;
CountPerDocument(String documentId, int count)
{
this.documentId = documentId;
this.count = count;
}
public String getDocumentId()
{
return this.documentId;
}
public int getCount()
{
return this.count;
}
}
After that, I am trying to print the TreeMap into a text file as <DocID - Count>
Not sure what I am doing wrong here, but the output I get is as follows:
The Stem is todai:[CountPerDocument#5caf905d, CountPerDocument#27716f4, CountPerDocument#8efb846, CountPerDocument#2a84aee7, CountPerDocument#a09ee92, CountPerDocument#30f39991]
Wondering if anyone can guide me what i am doing wrong and if my method isn't correct what am i supposed to do?
public class StemTreeMap
{
private static final String r1 = "\\$DOC";
private static final String r2 = "\\$TITLE";
private static final String r3 = "\\$TEXT";
private static Pattern p1,p2,p3;
private static Matcher m1,m2,m3;
public static void main(String[] args)
{
BufferedReader rd,rd1;
String docid = null;
String id;
int tf = 0;
//CountPerDocument cp = new CountPerDocument(docid, count);
List<CountPerDocument> ls = new ArrayList<>();
Map<String,List<CountPerDocument>> mp = new TreeMap<>();
try
{
rd = new BufferedReader(new FileReader(args[0]));
rd1= new BufferedReader(new FileReader(args[0]));
int docCount = 0;
String line = rd.readLine();
p1 = Pattern.compile(r1);
p2 = Pattern.compile(r2);
p3 = Pattern.compile(r3);
while(line != null)
{
m1 = p1.matcher(line);
m2 = p2.matcher(line);
m3 = p3.matcher(line);
if(m1.find())
{
docid = line.substring(5, line.length());
docCount++;
//System.out.println("The Document ID is :");
//System.out.println(docid);
line = rd.readLine();
}
if(m2.find()||m3.find())
{
line = rd.readLine();
}
else
{
if(!(mp.containsKey(line))) // if the stem is not on the TreeMap
{
//System.out.println("The stem is not present in the tree");
tf = 1;
ls.add(new CountPerDocument(docid,tf));
mp.put(line, ls);
line = rd.readLine();
}
else
{
if(ls.indexOf(docid) > 0) //if its last entry matches the current document number
{
//System.out.println("The Stem is present for the same docid so incrementing docid");
tf = tf+1;
ls.add(new CountPerDocument(docid,tf));
line = rd.readLine();
}
else
{
//System.out.println("Stem is present but not the same docid so inserting new docid");
tf = 1;
ls.add(new CountPerDocument(docid,tf)); //set did to the current document number and tf to 1
line = rd.readLine();
}
}
}
}
rd.close();
System.out.println("The Number of Documents in the file is:"+ docCount);
//Write to an output file
String l = rd1.readLine();
File f = new File("dictionary.txt");
if (f.createNewFile())
{
System.out.println("File created: " + f.getName());
}
else
{
System.out.println("File already exists.");
Path path = Paths.get("dictionary.txt");
Files.deleteIfExists(path);
System.out.println("Deleted Existing File:: Creating New File");
f.createNewFile();
}
FileWriter fw = new FileWriter("dictionary.txt");
fw.write("The Total Number of Stems: " + mp.size() +"\n");
fw.close();
System.out.println("The Stem is todai:" + mp.get("todai"));
}catch(IOException e)
{
e.printStackTrace();
}
}
}
You didn't define the function String toString() in your class CountPerDocument. So, when you try to print a CountPerDocument variable, the default printed value is CountPerDocument#hashcode.
To decide how to represent a CountPerDocument variable in your code, add in your class the next function:
#Override
public String toString() {
return "<" + this.getDocumentId() + ", " + this.getCount() + ">";
}
Try to override toString method in CountPerDocument. Something like this:
public class CountPerDocument
{
private final String documentId;
private final int count;
CountPerDocument(String documentId, int count)
{
this.documentId = documentId;
this.count = count;
}
public String getDocumentId()
{
return this.documentId;
}
public int getCount()
{
return this.count;
}
#Override
public String toString() {
return documentId + "-" + count;
}
}

How to overwrite integer at specific part of text file?

I have a textfile called "BookDetails.txt"
It is formatted in Book Title, Author, Publisher, Branch Call Number, and # of Copies like so:
1984 : George Orwell : Penguin : FIC Orw : 23
In my program, I am trying to overwrite the number of copies from 23 to 22 (decrementing by one essentially) when a patron checks out the specific book
public class CheckOutDialog extends javax.swing.JDialog {
private static final DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
ArrayList<CheckOut> checkOuts = new ArrayList<CheckOut>();
String bookTitle;
int numberOfCopies;
/**
* Creates new form CheckOutDialog
*/
public CheckOutDialog(java.awt.Frame parent, boolean modal) {
super(parent, modal);
initComponents();
Date currentDate = new Date();
jTextFieldDate.setText(df.format(currentDate));
}
private void jButtonCheckOutActionPerformed(java.awt.event.ActionEvent evt) {
String firstName = jTextFieldFirstName.getText();
String lastName = jTextFieldLastName.getText();
bookTitle = jTextFieldBookTitle.getText();
String checkOutDate = jTextFieldDate.getText();
CheckOut checkOutInfo = new CheckOut(firstName, lastName, bookTitle, checkOutDate);
checkOuts.add(checkOutInfo);
CheckOutCopy();
}
public void CheckOutCopy() //This method checks for book and num of copies
{
try {
File f = new File("BookDetails.txt");
Scanner fileRead = new Scanner(f);
boolean foundTitle = false;
fileRead.nextLine();
while(fileRead.hasNextLine())
{
String textLine = fileRead.nextLine();
String[] bookInfo = textLine.split(" : ");
String tempBookTitle = bookInfo[0];
numberOfCopies = Integer.parseInt(bookInfo[4]);
if(tempBookTitle.trim().equals(bookTitle))
{
foundTitle = true;
break;
}
}
if(foundTitle && numberOfCopies > 0)
{
OverwriteCopies();
WriteCheckOut();
this.setVisible(false);
}
else if(numberOfCopies == 0)
{
if(JOptionPane.showConfirmDialog(null, "Would you like to add the patron to the queue?", "No copies available", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION)
{
AddPatronQueue();
}
else
{
JOptionPane.getRootFrame().dispose();
}
}
else
{
JOptionPanes.messageBox("Book was not found in Library Catalog", "Check Out Error");
}
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
}
private void OverwriteCopies()
{
numberOfCopies--;
//Unsure how to proceed from here
}
private void WriteCheckOut()
{
WriteFile wf = new WriteFile("CheckOutDetails.txt");
for(int i = 0; i < checkOuts.size(); i++)
{
CheckOut c = checkOuts.get(i);
String checkOutDetails = c.getFirstName() + " : " + c.getLastName() + " : " + c.getBookTitle() + " : " + c.getCheckOutDate();
wf.write(checkOutDetails);
}
wf.close();
}
My program is successful in finding a specific book and its number of copies (and it produces the JOptionPane if it has 0 copies left). However, I am unsure of how I can overwrite and update that specific element within the text file. I have done some research and it seems that RandomAccessFile may be one possible option. Is the RAF the viable solution to my problem or is there another option that I can take?

Needing to update my outfile after items are changed

For my program I have it set up that I can edit and change values of items that are stored within my outfile in the program itself. However the numbers that they change to only update in the program itself. For example if I sell 10 ketchups than in my program i would have 0 but my outfile would still say I have 10. I need my outfile to update with my program. I came up with an override method but all it does currently is adds content on a new line within the outfile, I am not sure how I would go about actually updating any information stored on the outfile any help would be great.
Code:
public class Driver {
public static ArrayList<Item> list = new ArrayList<Item>();
static double myBalance = 100;
/*static ArrayList<Item> list = new ArrayList<Item>();*/
/**
* #param args
* #throws IOException
* #throws FileNotFoundException
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
ArrayList<String> inventoryList = new ArrayList<String>();
BufferedReader readIn = null;
try {
readIn = new BufferedReader(new FileReader("inventory.out"));
readIn.lines().forEach(inventoryList::add);
} catch (Exception e) {
e.printStackTrace();
} finally {
if(readIn != null) {
readIn.close();
}
}
for (int i = 0; i < 4; i++) {
String item = inventoryList.get(i);// input String like the one you would read from a file
String delims = "[,]"; //delimiter - a comma is used to separate your tokens (name, qty,cost, price)
String[] tokens = item.split(delims); // split it into tokens and place in a 2D array.
String name = tokens[0]; System.out.println(name);
double cost = Double.parseDouble(tokens[1]);System.out.println(cost);
int qty = Integer.parseInt(tokens[2]);System.out.println(qty);
double price = Double.parseDouble(tokens[3]);System.out.println(price);
list.add(new Item(name, cost, qty, price));
}
sell("Mayo", 10);
buy("Ketchup", 20);
remove_item("Ketchup");
add_item("Tums", 20, 10, 5);
overwrite("New line");
PrintAll();
}
// Method to sell items from the arraylist
public static void sell(String itemName, int amount) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getName().equals(itemName)) {
int number = i;
list.get(number).qty -= amount;
myBalance += list.get(number).getPrice() * amount;
}
}
}
// Method to buy more of the items in our array list
public static void buy(String itemName, int amount) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getName().equals(itemName)) {
int number = i;
list.get(number).qty += amount;
myBalance -= list.get(number).getPrice() * amount;
}
}
}
// Method to remove an item completely from our inventory
public static void remove_item(String itemName) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).getName().equals(itemName)) {
int number = i;
list.remove(number);
}
}
}
public static void add_item(String itemName, double itemCost, int qty, double itemPrice) {
list.add(new Item(itemName, itemCost, qty, itemPrice));
}
public static void PrintAll() {
String output = "";
for(Item i : list) {
int everything = i.getQty();
String everything2 = i.getName().toString();
output += everything +" "+ everything2 + "\n";
}
JOptionPane.showMessageDialog(null, "Your current balance is: $" + myBalance + "\n" + "Current stock:" + "\n" + output);
}
public static void overwrite(String update) {
try
{
String filename= "inventory.out";
FileWriter fw = new FileWriter(filename,true); //the true will append the new data
fw.write("\n"+"add a line");//appends the string to the file
fw.close();
}
catch(IOException ioe)
{
System.err.println("IOException: " + ioe.getMessage());
}
}
}
Outfile contents:
Ketchup,1,10,2
Mayo,2,20,3
Bleach,3,30,4
Lysol,4,40,5
If you know the name of your outfile then clear the outfile as and when you need it updated and then write to it again. You can use the below code to erase content of a file.
PrintWriter writer = new PrintWriter(file);
writer.print("");
writer.close();

Writing into multiple files using multithreading and limiting the write count to 20000 in each file

I have a complicated situation here,..
I am developing an multithreaded application There are 5 threads which i am creating and using these threads i want to write a program to write into 5 files simultaneously and also limiting the number of data to 20000. I am getting data from DB. The data is different for all the 5 threads. So the correct data should go into each file. Also, each thread also needs to access correct filewriter inorder to write correct data in correct file and have counter for each file.
public class AuditMissingRelationshipGuidEntitiesToXml
{
private Logger logger = ERDLoggerUtility.getLogger( this.getClass().getName());
private DbPartitionedConnections myDbPConn = null;
private RelationshipRepositoryDao myRRDao = null;
private MrdPartitionedConnections myMRDPartitionConn = null;
private MasterRecordDao myMRDRDao = null;
private String myCollectionName = null;
private String myOutputDir = null;
private String myOutputFileName = null;
private EntityFileWriter myEntityFileWriter = null;
private NovusDocumentGuidCaseFinder novusDocGuidCaseFinder = null;
//private int entityFileWriterCount = 0;
private static List <String> collections = new ArrayList<String>();
private static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
private BasicDataSource ds;
private static final int NTHREADS = 30;
private void setupDatabases() throws Exception {
ErdProperties props = ErdProperties.getProps();
this.myDbPConn = new RrdPartitionedConnections();
this.myRRDao = new OracleRelationshipRepositoryDao(this.myDbPConn);
this.myMRDPartitionConn = new MrdPartitionedConnections();
this.myMRDRDao = new OracleMasterRecordDao(this.myMRDPartitionConn);
ds = new BasicDataSource();
ds.setDriverClassName(DBDRIVER);
ds.setUrl(props.getProperty("wfdb.uri"));
ds.setUsername(props.getProperty("wfdb.user"));
ds.setPassword(props.getProperty("wfdb.password"));
novusDocGuidCaseFinder = new NovusDocumentGuidCaseFinder(ds);
novusDocGuidCaseFinder.setNovusCollection(myCollectionName);
}
private void setCommandLineProperties(String[] theArgs) throws Exception {
if (theArgs == null || theArgs.length != 3 ||
theArgs[0] == null || theArgs[0].length() == 0 ||
theArgs[1] == null || theArgs[1].length() == 0 ||
theArgs[2] == null || theArgs[2].length() == 0) {
System.err.println("You must provide 3 arguments! See below.");
System.err.println("\t1st Argument) -- Output directory location. ex: \"/ct-data/RRDGuids\"");
System.err.println("\t2nd Argument) -- Output file name. ex: \"rrd_seq_guid\"");
System.err.println("\t3rd Argument) -- Collection name. ex: \"N_ARREST\"");
throw new Exception("Invalid Arguments, see console output.");
}
else {
// Set the output directory location
this.myOutputDir = theArgs[0];
System.out.println("setCommandLineProperties() -- 1st Argument) Input directory location = [" + this.myOutputDir + "]");
// Set the output file name
this.myOutputFileName = theArgs[1];
System.out.println("setCommandLineProperties() -- 1st Argument) Input file name = [" + this.myOutputFileName + "]");
// Set the output file name
//this.myCollectionName = theArgs[2];
//System.out.println("setCommandLineProperties() -- 3nd Argument) Collection name = [" + this.myCollectionName + "]");
}
}
/**
* Add the rel seq and entity guid.
*
* #param theRelSeq
* #param theEntityGuid
* #throws Exception
*/
private synchronized void addEntity(String theRelSeq, String theEntityGuid,
String theRelGuid, EntityFileWriter myEntityFileWriter) throws Exception {
/*
if (this.myEntityFileWriter == null) {
System.out.println("file for :"+collectionName);
this.myEntityFileWriter = new EntityFileWriter(new File(myOutputDir), myOutputFileName, collectionName, System.currentTimeMillis());
}
*/
myEntityFileWriter.addEntity(theRelSeq, theEntityGuid, theRelGuid);
}
private Set<String> locateEntityGuidsInMRD(List<String> theRRDGuids, String collectionName) throws Exception {
Set<String> foundEntityGuids = new HashSet<String>();
System.out.println("Searching MRD for entity guids (AKA: BASE_GUID)... for : " + collectionName);
MasterRecordDao myMRDRDao = null;
synchronized(collectionName.intern()){
myMRDRDao = new OracleMasterRecordDao(this.myMRDPartitionConn);
/*for(String li : theRRDGuids){
System.out.println(li);
}*/
List<PersonEntity> personEntities = myMRDRDao.getByEntityGuid(theRRDGuids);
System.out.println("Found: " + (personEntities == null ? "0" : personEntities.size()) + " entities in MRD for :" + collectionName);
if (personEntities != null) {
for (PersonEntity pe : personEntities) {
foundEntityGuids.add(pe.getEntityGuid());
}
}
this.notify();
}
myMRDRDao=null;
return foundEntityGuids;
}
public void determineOrphanRelationships(String collectionName) throws Exception {
Long startTime = null;
Long endTime = null;
startTime = System.currentTimeMillis();
System.out.println("Started on: " + new Timestamp(startTime).toString() + "::" + collectionName);
synchronized(collectionName.intern()){
EntityFileWriter myEntityFileWriter = null;
Map<EntityDocRelationship, String> entityDocRels = new HashMap<EntityDocRelationship, String>();
EntityDocRelationshipIterator entityDocRelIter = myRRDao.getByCollection(collectionName);
int entityFileWriterCount = 0;
while (entityDocRelIter.hasNext()) {
/*
* Reference: OracleRelationshipRepositoryDao.populateFrom()
*
* EntityDocRelationship.getPk() = EntityDocRelationship.REL_SEQ (1st column in prepared statement)
* EntityDocRelationship.getRelGuid() = EntityDocRelationship.REL_GUID (4th position in prepared statement)
* EntityDocRelationship.getEntityGuid() = EntityDocRelationship.BASE_GUID (5th position in prepared statement)
* EntityDocRelationship.getDocGuid() = EntityDocRelationship.TARGET_GUID (6th position in prepared statement)
*/
if(entityDocRels.size() < 20000) {
EntityDocRelationship entityDocRel = (EntityDocRelationship)entityDocRelIter.next();
entityDocRels.put(entityDocRel, entityDocRel.getEntityGuid());
}
else{
entityFileWriterCount = printNotFoundEntityGuids(entityDocRels, collectionName,
entityFileWriterCount, myEntityFileWriter, false);
}
this.wait();
}
if(entityDocRels.size() > 0){
entityFileWriterCount = printNotFoundEntityGuids(entityDocRels, collectionName,
entityFileWriterCount, myEntityFileWriter, true);
endTime = System.currentTimeMillis();
entityFileWriterCount = 0;
System.out.println("Ended on:" + endTime);
System.out.println("Run time: " + (endTime - startTime));
}
}
}
private int printNotFoundEntityGuids(Map<EntityDocRelationship, String> entityDocRels, String collectionName,
int entityFileWriterCount, EntityFileWriter myEntityFileWriter, boolean closeWriter) throws Exception{
// Do work with the distinct set of entity guids.
Set<String> foundEntityGuids = locateEntityGuidsInMRD(new ArrayList<String>(entityDocRels.values()), collectionName);
System.out.println(foundEntityGuids.size());
System.out.println("Printing not found entity guid list...");
for (Map.Entry<EntityDocRelationship, String> entry : entityDocRels.entrySet()) {
if (!foundEntityGuids.contains(entry.getValue())) {
synchronized(this){
if (entityFileWriterCount == 0) {
System.out.println("file for :"+collectionName);
myEntityFileWriter = new EntityFileWriter(new File(myOutputDir), myOutputFileName,
collectionName, System.currentTimeMillis());
}
entityFileWriterCount++;
addEntity(String.valueOf(entry.getKey().getPk()), entry.getValue(), entry.getKey().getRelGuid(), myEntityFileWriter);
System.out.println(collectionName + " :: Relationship pk: " + entry.getKey().getPk() + " is orphan to Entity: " + entry.getValue());
System.out.println("Finished printing.");
if(closeWriter || entityFileWriterCount >= 10){
System.out.println("Closing file writer...");
if (this.myEntityFileWriter != null) {
this.myEntityFileWriter.endDocument();
this.myEntityFileWriter=null;
}
System.out.println("File writer closed.");
}
}
}
}
return entityFileWriterCount;
}
public void deleteRelationships(final String collectionName) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
File outputDir = new File(this.myOutputDir);
FilenameFilter filter = new FilenameFilter() {
public boolean accept(File dir, String name) {
return name.startsWith("rrd_seq_guid_"+collectionName);
}
};
String[] files = outputDir.list(filter);
for (String file : files) {
logger.info("Getting relationships from file: " + file + "...");
EntityFileHandler parsedFile = new EntityFileHandler();
saxParser.parse(this.myOutputDir + file, parsedFile);
Map<String, String> relSeqsGuids = new HashMap<String, String>();
for (EntityFileHandler.EntityFile entityFile : parsedFile.getDocuments()){
relSeqsGuids.put(entityFile.getRelSeq(), entityFile.getRelGuid());
}
/*logger.info("Deleting relationship sequence guids...");
myRRDao.deleteRelSeqGuids(relSeqsGuids.keySet());
logger.info("Relationship sequence guids deleted.");*/
/*
logger.info("Validating relationship guids in Novus...");
List<String> validNovusRelGuids = novusDocGuidCaseFinder.search(
relSeqsGuids.values().toArray(new String[relSeqsGuids.values().size()]));
logger.info("Relationship guids are valid in Novus.");*/
List<String> validNovusRelGuids = new ArrayList<String>();
validNovusRelGuids.addAll(relSeqsGuids.values());
logger.info("Sending delete files to Novus...");
sendDeleteFileToNovus(file, validNovusRelGuids, collectionName);
logger.info("Delete files sent.");
}
}
/**
* This method will send delete files to Novus based on the list
* of relationship Guids passed in.
*
* Example delete file:
*
* <deletes>
* <collection>
* <name>...</name>
* <guid></guid>
* .
* . N times
* .
* <guid></guid>
* </collection>
* </deletes>
*
* #param theRelGuids - ERD Relationship Guids to send a delete file for.
* #throws Exception
*/
public void sendDeleteFileToNovus(String theFile, List<String> theRelGuids, String collectionName) {
logger.info("Sending delete files to Novus...");
try{
Document document = new DocumentImpl();
// Create the Delete Element (aka: root): <Deletes>
Element deleteElement = document.createElement("deletes");
/*
* Create the Collection Element <Collection> and then add it to the Deletes Element.
*
* <deletes>
* <collection></collection>
* </deletes>
*/
Element collectionElement = document.createElement("collection");
deleteElement.appendChild(collectionElement);
/*
* Create the Name Element <Name> with the Collection name
* and then add it to the Collection Element.
*
* <deletes>
* <collection>
* <name>...</Name>
* </collection>
* </deletes>
*/
Element nameElement = document.createElementNS(null, "name");
nameElement.appendChild(document.createTextNode(collectionName));
collectionElement.appendChild(nameElement);
if (theRelGuids != null && theRelGuids.size() > 0) {
/*
* For each Relationship Guid add a Guid Element to the Collection
* Element with the Relationship Guid.
*
* <deletes>
* <collection>
* <name>...</name>
* <guid>...</guid>
* </collection>
* </deletes>
*/
for(String relGuid : theRelGuids){
Element relGuidElement = document.createElementNS(null, "guid");
relGuidElement.appendChild(document.createTextNode(relGuid));
collectionElement.appendChild(relGuidElement);
}
}
logger.info("Add delete element text content: " + deleteElement.getTextContent());
document.appendChild(deleteElement);
String deleteFile =
File.separator + "ct-data" +
File.separator + "erd" +
File.separator + "wip" +
File.separator + "relAtishDeletes" +
File.separator + theFile;
logger.info("Creating Novus delete file: " + deleteFile + "...");
FileOutputStream outStream = new FileOutputStream(deleteFile);
OutputFormat of = new OutputFormat("XML","ISO-8859-1",true);
of.setIndent(1);
of.setIndenting(true);
XMLSerializer serializer = new XMLSerializer(outStream, of);
serializer.asDOMSerializer();
serializer.serialize(document.getDocumentElement());
outStream.close();
logger.info("Delete file: " + deleteFile + " created.");
}
catch(Exception e){
e.printStackTrace();
}
/*MatchManageCommand mmc = new MatchManageCommand();
String publishXML = mmc.getPublishXml(-1, this.myCollectionName, "-1", theFile);
mmc.ms.putMessageOnQueue(publishXML, 2);*/
}
public void getCollections()
{
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = ds.getConnection();
String query = "select novus_collection from erd_workflow.collection_info " +
"where Novus_collection in ('N-SALE', 'N-UCC00', 'N-UCC01', 'N-UCC02', 'N-UCC03') order by novus_collection asc";
statement = connection.createStatement();
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
// Store the Novus Collection and associated Product.
collections.add(resultSet.getString(1));
}
}
catch (SQLException sqle) {
sqle.printStackTrace();
} catch(Exception e){
e.printStackTrace();
}
finally {
if (resultSet != null) {
try {
resultSet.close();
statement.close();
connection.close();
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
}
public static void main(String[] args) throws Exception{
AuditMissingRelationshipGuidEntitiesToXml audit = new AuditMissingRelationshipGuidEntitiesToXml();
ExecutorService executor = Executors.newFixedThreadPool(NTHREADS); // makes thread pool
try {
audit.setupDatabases();
audit.getCollections();
audit.setCommandLineProperties(args);
//audit.runThreads(0, collections.size());
int start = 0;
while(start < collections.size()){
Runnable worker = audit.new RunThreads(audit, collections.get(start) );
/*
* Executes the given command at some time in the future. The command
* may execute in a new thread, in a pooled thread, or in the calling
* thread*/
executor.execute(worker);
start++; // increment to get next collection
}
/*
* Initiates an orderly shutdown in which previously submitted
* tasks are executed, but no new tasks will be
* accepted. Invocation has no additional effect if already shut
* down. */
executor.shutdown();
System.out.println("Finished all threads");
// System.out.println("done with current threads..... creating new threads... ");
}catch(InterruptedException e) {
System.out.println("Interrupted :");
e.printStackTrace();
}catch(RejectedExecutionException e){
e.printStackTrace();
}
}
public String getMyCollectionName() {
return myCollectionName;
}
public void setMyCollectionName(String myCollectionName) {
this.myCollectionName = myCollectionName;
}
public class RunThreads implements Runnable{
AuditMissingRelationshipGuidEntitiesToXml auditThread;
private String myCollection;
private int sleepTime; // random sleep time for thread
private Random generator = new Random();
public RunThreads(AuditMissingRelationshipGuidEntitiesToXml audit, String collection){
try{
this.auditThread = audit;
myCollection = collection;
// pick random sleep time between 0 and 5 seconds
sleepTime = generator.nextInt(20000);
}catch(Exception e){
System.out.println("Interrupted");
}
}
/* Synchronize the AuditMissingRelationshipGuidEntitiesToXml object and call the methods on the particular object */
public void run() {
synchronized(this.myCollection.intern()) { // synchronized block
try {
//Thread.sleep(sleepTime);
System.out.println("Collection started : "+ this.myCollection);
this.auditThread.determineOrphanRelationships(this.myCollection);
this.auditThread.deleteRelationships(this.myCollection);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

How to parse a String into multiple arrays

Good day!
I am making a mini bookstore program and we are required to read a file based from what the customer buys on the specified counter as follows:
counter 4,book1 2,book2 2,book3 2,tender 100.00
counter 1,book1 2,book2 1,book3 3, book4 5,tender 200.00
counter 1,book3 1,tender 50.00
In short the format is:
COUNTER -> ITEMS BOUGHT -> TENDER
I tried doing this but it is not that efficient:
public List<String> getOrder(int i) {
List <String> tempQty = new ArrayList<String>();
String[] orders = orderList.get(0).split(",");
for (String order : orders) {
String[] fields = order.split(" ");
tempQty.add(fields[i]);
}
return tempQty;
}
How can i read the file and at the same time, ensures that I will put it on the correct array? Besides the counter and the tender, I need to know the name of the book and the qty so I could get its price and computer for the total price. Do I need to do multiple arrays to store each values? Any suggestions/ codes will be
highly appreciated.
Thank you.
Map<String, Integer> itemsBought = new HashMap<String, Integer>();
final String COUNTER = "counter";
final String TENDER = "tender";
String[] splitted = s.split(",");
for (String str : splitted) {
str = str.trim();
if (str.startsWith(COUNTER)) {
//do what you want with counter
} else if (str.startsWith(TENDER)) {
//do what you want with tender
} else {
//process items, e.g:
String[] itemInfo = str.split(" ");
itemsBought.put(itemInfo[0], Integer.valueOf(itemInfo[1]));
}
}
How about this? Here we have a class that is modeling a purchase, containing counter, tender and a list of the bought items. The bought item consists of an id (e.g. book1) and a quantity. Use the method readPurchases() to read the contents of a file and get a list of purchases.
Does this solve your problem?
public class Purchase {
private final int counter;
private final List<BoughtItem> boughtItems;
private final double tender;
public Purchase(int counter, List<BoughtItem> boughtItems, double tender) {
this.counter = counter;
this.boughtItems = new ArrayList<BoughtItem>(boughtItems);
this.tender = tender;
}
public int getCounter() {
return counter;
}
public List<BoughtItem> getBoughtItems() {
return boughtItems;
}
public double getTender() {
return tender;
}
}
public class BoughtItem {
private final String id;
private final int quantity;
public BoughtItem(String id, int quantity) {
this.id = id;
this.quantity = quantity;
}
public String getId() {
return id;
}
public int getQuantity() {
return quantity;
}
}
public class Bookstore {
/**
* Reads purchases from the given file.
*
* #param file The file to read from, never <code>null</code>.
* #return A list of all purchases in the file. If there are no
* purchases in the file, i.e. the file is empty, an empty list
* is returned
* #throws IOException If the file cannot be read or does not contain
* correct data.
*/
public List<Purchase> readPurchases(File file) throws IOException {
List<Purchase> purchases = new ArrayList<Purchase>();
BufferedReader lines = new BufferedReader(new FileReader(file));
String line;
for (int lineNum = 0; (line = lines.readLine()) != null; lineNum++) {
String[] fields = line.split(",");
if (fields.length < 2) {
throw new IOException("Line " + lineNum + " of file " + file + " has wrong number of fields");
}
// Read counter field
int counter;
try {
String counterField = fields[0];
counter = Integer.parseInt(counterField.substring(counterField.indexOf(' ') + 1));
} catch (Exception ex) {
throw new IOException("Counter field on line " + lineNum + " of file " + file + " corrupt");
}
// Read tender field
double tender;
try {
String tenderField = fields[fields.length - 1];
tender = Double.parseDouble(tenderField.substring(tenderField.indexOf(' ') + 1));
} catch (Exception ex) {
throw new IOException("Tender field on line " + lineNum + " of file " + file + " corrupt");
}
// Read bought items
List<BoughtItem> boughtItems = new ArrayList<BoughtItem>();
for (int i = 1; i < fields.length - 1; i++) {
String id;
int quantity;
try {
String bookField = fields[i];
id = bookField.substring(0, bookField.indexOf(' '));
quantity = Integer.parseInt(bookField.substring(bookField.indexOf(' ') + 1));
BoughtItem boughtItem = new BoughtItem(id, quantity);
boughtItems.add(boughtItem);
} catch (Exception ex) {
throw new IOException("Cannot read items from line " + lineNum + " of file " + file);
}
}
// We're done with this line!
Purchase purchase = new Purchase(counter, boughtItems, tender);
purchases.add(purchase);
}
return purchases;
}
}

Categories

Resources