Related
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;
}
}
I have a csv file which is hashmapped, whenever the user enter the city name(key) it will display all the details of that city. I have to optimize the search result time, everytime the it is reading the file(instead of only once) and displaying the values.
The CSV files contains data like this :
city,city_ascii,lat,lng,country,iso2,iso3,admin_name,capital,population,id
Malishevë,Malisheve,42.4822,20.7458,Kosovo,XK,XKS,Malishevë,admin,,1901597212
Prizren,Prizren,42.2139,20.7397,Kosovo,XK,XKS,Prizren,admin,,1901360309
Zubin Potok,Zubin Potok,42.9144,20.6897,Kosovo,XK,XKS,Zubin
Potok,admin,,1901608808
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Scanner;
import java.io.IOException;
public class CSVFileReaders{
public static void main(String[] args) {
String filePath = "C:\\worldcities1.csv";
Scanner in = new Scanner(System.in);
System.out.println(" \n Enter the City name to be Searched : \n _> ");
long start = System.currentTimeMillis();
String searchTerm = in.nextLine();
readAndFindRecordFromCSV(filePath, searchTerm);
long end = System.currentTimeMillis();
System.out.println(" \n It took " + (end - start) + " Milli Seconds to search the result \n");
in.close();
}
public static void readAndFindRecordFromCSV( String filePath, String searchTerm) {
try{
HashMap<String,ArrayList<String>> cityMap = new HashMap<String,ArrayList<String>>();
Scanner x = new Scanner (new File(filePath),"UTF-8");
String city= "";
while(x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for(int i=0;i<line.length;i++){
values.add(line[i]);
}
cityMap.put(city,values);
}
x.close();
//Search the city
if(cityMap.containsKey(searchTerm)) {
System.out.println("City name is : "+searchTerm+"\nCity details are accordingly in the order :"
+ "\n[city , city_ascii , lat , lng , country , iso2 , iso3 , admin_name , capital , population , id] \n"
+cityMap.get(searchTerm)+"");
}
else {
System.out.println("Enter the correct City name");
}
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}`
the time should be optimized and every time i search it is reading the entire file(which should happen)
Currently you mix the map initialization inside the search function.
You don't want that.
First, init the map, then use it in the search function.
To do that, extract a method for statements that instantiate and value the map and then refactor the readAndFindRecordFromCSV() method so that it accepts a Map as additional parameter :
public static void readAndFindRecordFromCSV( String filePath, String searchTerm, HashMap<String,ArrayList<String>> dataByCity) {...}
With refactoring IDE features, it should be simple enough : "extracting method" then "change signature".
Here is a code (not tested at runtime but tested at compile time) that splits the logical in separated tasks and also rely on instance methods :
public class CSVFileReaders {
private final String csvFile;
private HashMap<String, ArrayList<String>> cityMap;
private final Scanner in = new Scanner(System.in);
public static void main(String[] args) {
String filePath = "C:\\worldcities1.csv";
CSVFileReaders csvFileReaders = new CSVFileReaders(filePath);
csvFileReaders.createCitiesMap();
csvFileReaders.processUserFindRequest(); // First search
csvFileReaders.processUserFindRequest(); // Second search
}
public CSVFileReaders(String csvFile) {
this.csvFile = csvFile;
}
public void createCitiesMap() {
cityMap = new HashMap<>();
try (Scanner x = new Scanner(new File(csvFile), "UTF-8")) {
String city = "";
while (x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for (int i = 0; i < line.length; i++) {
values.add(line[i]);
}
cityMap.put(city, values);
}
x.close();
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
}
public void processUserFindRequest() {
System.out.println(" \n Enter the City name to be Searched : \n _> ");
long start = System.currentTimeMillis();
String searchTerm = in.nextLine();
long end = System.currentTimeMillis();
System.out.println(" \n It took " + (end - start) + " Milli Seconds to search the result \n");
//Search the city
if (cityMap.containsKey(searchTerm)) {
System.out.println("City name is : " + searchTerm + "\nCity details are accordingly in the order :"
+ "\n[city , city_ascii , lat , lng , country , iso2 , iso3 , admin_name , capital , population , id] \n"
+ cityMap.get(searchTerm) + "");
} else {
System.out.println("Enter the correct City name");
}
}
}
The interesting part is here :
String filePath = "C:\\worldcities1.csv";
CSVFileReaders csvFileReaders = new CSVFileReaders(filePath);
csvFileReaders.createCitiesMap();
csvFileReaders.processUserFindRequest(); // First search
csvFileReaders.processUserFindRequest(); // Second search
The logical is clearer now.
Why do you create / load the CSV into a HashMap with every search ?
Just create the HashMap only once in the beginning, and then on every search just check whether it exists in the HashMap, eg move the read part into a separate method :
HashMap<String,ArrayList<String>> cityMap = new HashMap<String,ArrayList<String>>();
public static void readCSVIntoHashMap( String filePath) {
try{
Scanner x = new Scanner (new File(filePath),"UTF-8");
String city= "";
while(x.hasNextLine()) {
ArrayList<String> values = new ArrayList<String>();
String name = x.nextLine();
//break each line of the csv file to its elements
String[] line = name.split(",");
city = line[1];
for(int i=0;i<line.length;i++){
values.add(line[i]);
}
cityMap.put(city,values);
}
x.close();
...
}
Then have a separate method for searching :
public static void search(String searchTerm) {
if(cityMap.containsKey(searchTerm)) {
...
}
}
Is their an easy way to pass the variables and arrays between these methods without having a super long method signature? Currently I am using these statics but I know that's not the "correct" way of doing it but if I pass them in the signature it starts to make everything look ugly. So what would be the "correct" way to pass the variables like lastName, firstName, and role?
// Program wide variables
//static String firstName; // First name from the file
static String lastName; // Last name from the file
static String username; // Username
static String password;
static String role;
static String email;
static String answersFile; // Answers file in use with path and ext
static String[] answeredQ = new String[questAsks]; // Recording the question asked
static Boolean[] answeredA = new Boolean[questAsks]; //Recording users answer
static Boolean[] answeredC = new Boolean[questAsks]; //Recording the correct answer
public static void main(String Args[]) throws FileNotFoundException, IOException {
// Main method that contains major control functions; a quick summary of the program; magic
}
public static void quiz(String testType) throws HeadlessException, IOException {
String testBankFile = path + testType + ".txt";
Random rand = new Random();
int questionCount = 0, right = 0, wrong = 0;
long startTime = System.currentTimeMillis(); // Setting the start time in milliseconds
while (questionCount < questAsks) { // Loop that will ask all the questions
int r = rand.nextInt(getLines(testBankFile));
boolean ans = promptQuestion(read(r, testBankFile), questionCount + 1); // For some reason this makes it work
answeredQ[questionCount] = read(r, testBankFile);
answeredA[questionCount] = ans;
answeredC[questionCount] = parseA(read(r, answersFile));
if (ans != parseA(read(r, answersFile))) {
wrong++;
} else if (ans == parseA(read(r, answersFile))) {
right++;
}
questionCount++;
}
JOptionPane.showMessageDialog(null, "You got " + wrong + " wrong and " + right + " correct.");
long endDiff = (System.currentTimeMillis() - startTime);
makeReport(firstName, lastName, username, printTime(endDiff), testType, right);
}
// Generates a report report(first, last, score, time, array of answers)
public static void makeReport(String first, String last, String user, String time, String testType, int score) throws IOException {
DateFormat dateF = new SimpleDateFormat(dateFormat);
Date date = new Date();
String fileName = user + "_COSC236_Quiz_" + dateF.format(date) + ".txt";
File file = new File(fileName);
file.createNewFile();
FileWriter out = new FileWriter(fileName);
double percent = (((double) score) / ((double) questAsks) * 100);
out.write("Name: " + first + " " + last + "\n");
out.write("Score: " + percent + "%\n");
out.write("Elapsed time: " + time + "\n");
out.write("Test type: " + testType + "\n");
out.write("---------------------------------------------------------------------\n");
out.write(" Users\tCorrect\tQuestion\n");
for (int i = 0; i < answeredQ.length; i++) {
out.write(i + 1 + ".) ");
out.write(answeredA[i].toString() + "\t");
out.write(answeredC[i].toString() + "\t");
out.write(answeredQ[i] + "\n");
}
out.close();
}
// Boolean login method | login(tries allowed, source file)
public static void login(int tries, String source) throws FileNotFoundException, IOException {
String[] loginInfo;
boolean invalid = false;
for (int x = 0; x < tries; x++) {
invalid = false;
loginInfo = promptLogin();
if (loginInfo[0].toLowerCase().equals("done")) {
System.exit(0);
}
for (int i = 0; i < getLines(source); i++) {
StringTokenizer st = null;
st = new StringTokenizer(read(i, source));
String user = st.nextToken();
String pass = st.nextToken();
if (user.equals(loginInfo[0])) {
if (pass.equals(loginInfo[1])) {
username = loginInfo[0];
password = loginInfo[1];
firstName = st.nextToken();
lastName = st.nextToken();
email = st.nextToken();
role = st.nextToken();
if (role.toLowerCase().equals("instructor")) {
promptInstructor();
JOptionPane.showMessageDialog(null, exitedInstructorMode);
break;
} else {
run();
}
} else {
invalid = true;
}
} else {
invalid = true;
}
}
if(invalid) {
JOptionPane.showMessageDialog(null, invalidLogin);
}
}
JOptionPane.showMessageDialog(null, tooManyAttempts);
}
}
Why not just make a class that holds the values that you need to pass around
Use OOP. Create clss to you object
example:
class User{
String lastName;
String username;
String password;
String role;
String email;
...
public static User login(int tries, String source) throws FileNotFoundException, IOException {
//this you read User param and add new User
return user;
}
}
And now, where you need lastName, username, password, role or email, you can
pass User instance
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.
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;
}
}