Full width home advertisement

Post Page Advertisement [Top]


package com.masoomyf;
* com.masoomyf created by masoomyf on 28-01-2018.
//Class for bicycle parts, its attributes.
public class BicyclePart {
//For storing part number.
public long id;
//For storing part name.
public String name;
//For storing list price.
public double listPrice;
//For storing sale price.
public double salePrice;
//For storing onSale whether true or false.
public boolean onSale;
//For storing quantity.
public int quantity;
public BicyclePart(long id, String name, double listPrice, double sellPrice, boolean onSale,int quantity) {
//Initialize of new Object Bicycle part
//with the given value.
this.id = id;
this.name = name;
this.listPrice = listPrice;
this.salePrice = sellPrice;
this.onSale = onSale;
this.quantity = quantity;
//It will take string line like: akjs,1234567890,12.2,52.3,false,10 and
//convert it to bicycle object by splitting it with comma
//We use static here to call it directly without creating BicyclePart object.
//and will crete new Bicycle part and return it.
public static BicyclePart getPartFromString(String string){
//split function split the string and give its array.
//string example: akjs,1234567890,12.2,52.3,false,10
//ajks stores in 0 index, 1234567890 stores in 1 index and so on after splitting.
String[] parts = string.split(",");
//Creating new object with the split array and return it.
//Long.parseLong or Interger.parseInt or any other use to convert string object
//in the appropriate data type.
return new BicyclePart(Long.parseLong(parts[1]), parts[0],
public String toString(){
//just return all the attribute, with comma between them,
//to save it in database txt file.
return name + "," + id + "," + listPrice + "," + salePrice + "," + onSale;


package com.masoomyf;
import java.io.*;
import java.util.*;
public class Main {
//To store all bicycle parts.
private static ArrayList<BicyclePart> bicycleParts;
//flag if changes is made in database or not.
//if yes save it.
private static boolean databaseUpdated = false;
//main database file.
private static File wareHouseFile;
public static void main(String[] args) {
//initialize new ArrayList.
//Array list is use instead of array because it is expandable as
//well as it will collapse after deleting object.
bicycleParts = new ArrayList<>();
//Creating File object of database file.
wareHouseFile = new File("wareHouseDb.txt");
//for reading user input.
Scanner inputReader = new Scanner(System.in);
//Now check database file exists or not.
//If there is no Bicycle parts in database, or user run it first time
//Its return false, because there will be no database file.
// file is exists, try to read it.
try {
//reading main file.
//Creating file input stream to read file. and passing File object
//of database txt file.
FileInputStream inputStream = new FileInputStream(wareHouseFile);
//Creating buffered reader for file input stream.
//It's allow to read file line by line and many more options.
//but we need only to read line by line.
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//Creating String line, for storing each line of database file.
String line;
//loop until there is no new line available in database file.
//If there is no new line its return null and while loop breaks.
while ((line=reader.readLine())!=null){
//check whether line is empty or not.
//if line is empty get next line.
//If line is not empty perform the following.
//get new line from file and add it to bicycle.
//create new bicycle part and add it to arrayList.
BicyclePart bicyclePart = BicyclePart.getPartFromString(line);
}catch (Exception ignore){
//If we get any error during reading file.
//output error message.
System.out.println("Cant read ware house database.");
//Now display these option, until user write quit.
while (true){
//It will useful when user chooses an option another that quit,
//It allow user to read the previous message of console.
System.out.println("Press any key to continue.....");
//It will not continue until user press any button and enter.
//User pressed enter, it means user read the previous information.
//Now display menu again(or first time).
System.out.println("Please select your option from the following menu:");
System.out.println("Read: Read an inventory delivery file");
System.out.println("Enter: Enter a part");
System.out.println("Sell: Sell a part");
System.out.println("Display: Display a part");
System.out.println("SortName: Sort parts by part name");
System.out.println("SortNumber: Sort parts by part number");
System.out.print("Enter your choice: ");
//Now read the choice of user.
String choice = inputReader.nextLine();
//According to choice call the appropriate option.
else if(choice.equalsIgnoreCase("enter")){
else if(choice.equalsIgnoreCase("sell")){
else if(choice.equalsIgnoreCase("display")){
else if(choice.equalsIgnoreCase("sortName")){
else if(choice.equalsIgnoreCase("sortNumber")){
else if(choice.equalsIgnoreCase("quit")){
//If user select quit.
//save the database and break the loop.
else {
//If user writes another option other than provided menu.
//Give this error.
System.out.println("Invalid option chosen.");
//Reading file inventory.txt.
//Passing scanner here, so we don't need to create again a new scanner.
private static void readFile(Scanner inputReader) {
//prompt user to enter file name i.e. inventory.txt.
System.out.println("Enter file name to read from: ");
//read the fileName.
String fileName = inputReader.nextLine();
//Pass the filename to new File object.
//It will allow to check whether file is exists or not.
File file = new File(fileName);
//If file not exists display error message and return from this method.
System.out.println("Error: File not exists.");
//If file exists try the following.
try {
//Create a new scanner by passing file object of inventory.txt
//You can choose buffered reader also.
//Just learn new thing.
Scanner fileReader = new Scanner(file);
//Marking this line as nextLine.
//For future use.
//check if there is new line by looping.
while (fileReader.hasNextLine()){
//New line present, read the new line and store it into line.
String line = fileReader.nextLine();
//Now create a new Bicycle part.
BicyclePart temp = BicyclePart.getPartFromString(line);
//Now check, if this part exists in bicycleArrayList(database)
//by comparing the temp part number with every bicycle part's number
//store in array list(database)
for (BicyclePart bicyclePart:bicycleParts){
//Check if bicycle part is present or not.
//Yes present.
//Update it with new details, available in temp.
bicyclePart.listPrice = temp.listPrice;
bicyclePart.salePrice = temp.salePrice;
bicyclePart.onSale = temp.onSale;
//Add the quantity.
bicyclePart.quantity += temp.quantity;
//Flag the databaseUpdated to true.
//means save the database on exit, because it gets changed.
databaseUpdated = true;
//we use continue nextLine here because if we use only
//continue, for loop get's continue, and we don't it.
//so just skip the for loop and continue the while loop
//without executing the below lines.
//Below line is for new part's that are not available
//in our database.
continue nextLine;
//If there is no part that matches the temp, that's mean
//part is new and add it to database.
//Flag the databaseUpdated to true.
//means save the database on exit, because it gets changed.
}catch (Exception e){
//If something happen wrong, output the error.
System.out.println("Error: " + e.getMessage());
private static void enterPart(Scanner inputReader) {
//Prompt and read all parts info from user.
System.out.print("Enter part name: ");
String name = inputReader.nextLine();
//Below extra inputReader.nextLine is used because, we read a datatype
//other than string.
//If we don't call extra nextLine method, after reading this if we read a
//string, it will give us a new line.
//Example: we have to read an integer.
//we use inputReader.nextInteger().
//After that user write 45 or any number and press enter.
//45 passed to caller, and enter remains in scanner, and we try to read new
//line in future, it will just pass the enter which is in scanner.
//rather than wait for a new string user will enter.
System.out.print("Enter part number: ");
long id = inputReader.nextLong();
System.out.print("Enter list price: ");
double listPrice = inputReader.nextDouble();
System.out.print("Enter sell price: ");
double salePrice = inputReader.nextDouble();
System.out.print("Part is on sale? [true/false]: ");
boolean onSale = inputReader.nextBoolean();
System.out.println("Enter quantity: ");
int quantity = inputReader.nextInt();
//Now first check if bicycle part enter by user is present
//in database or not. If yes update it and stop the method execution.
for (BicyclePart bicyclePart: bicycleParts){
if(bicyclePart.id == id){
bicyclePart.listPrice = listPrice;
bicyclePart.salePrice = salePrice;
bicyclePart.onSale = onSale;
bicyclePart.quantity += quantity;
System.out.println("Bicycle part updated.");
databaseUpdated = true;
//If not add the new part to database.
BicyclePart bicyclePart = new BicyclePart(id,name,listPrice,salePrice,onSale,quantity);
System.out.println("New bicycle part is added.");
databaseUpdated = true;
//For selling part.
private static void sellPart(Scanner inputReader) {
System.out.println("Enter part number: ");
//Get the partNumber.
long partNumber = inputReader.nextLong();
//Remove the extra enter comes with long.
//Check part enter by user is present in database or not.
for (BicyclePart part: bicycleParts){
if(partNumber == part.id){
//if yes call sellPart(BicyclePart),
//this method is also sellPart but with different signature
//i.e. sellPart(Scanner).
//and stop executing this method.
//If part is present then this line never execute.
//If not present, this line will execute.
//And show error message.
System.out.println("Error: Bicycle part not exists.");
private static void sellPart(BicyclePart part){
//check quantity is not less than one.
//if yes give the error and stop execution of this method.
if(part.quantity < 1){
System.out.println("Error: No quantity left.");
//If quantity is more than zero(means available)
//Print the part name and its cost.
System.out.println("Part Name: " + part.name);
// here tertiary operator is used for taking decision in line.
// (true|false ? if true : if false)
System.out.println("Part Cost: " + (part.onSale?part.salePrice:part.listPrice));
System.out.println("Part is on sale.");
//Display the current date.
System.out.println("Sold Time: " + new Date().toString());
//decrease the part quantity.
//change the flag to true.
//if it changes by another method, no problem.
//For displaying part.
private static void displayPart(Scanner inputReader) {
System.out.print("Enter part name: ");
//read part name.
//here no extra inputReader.nextLine() is use because string is read.
//it automatically read the string with new line and omit it.
String partName = inputReader.nextLine();
//loop through database bicycle array list and check whether part name
//is available or not.
for (BicyclePart part: bicycleParts){
//if available call displayPart(BicyclePart) method.
//if no part is available display the error.
System.out.println("Error: Bicycle part not exists.");
//simple displayPart method.
private static void displayPart(BicyclePart part) {
System.out.println("Part Name: " + part.name);
System.out.println("Part Cost: " + (part.onSale?part.salePrice:part.listPrice));
//sortByName method.
private static void sortByName() {
//sort the arraylist with the help of new Comparator.
//java has compare option for datatype pre-defined in java,
//If we create a new datatype(i.e. class), we have to implement and override the compare
bicycleParts.sort(new Comparator<BicyclePart>() {
public int compare(BicyclePart o1, BicyclePart o2) {
//Compare the Bicycle Name with another one.
//Java has string compare method.
//so we use here and return the compare value to Comparator.
return o1.name.compareToIgnoreCase(o2.name);
//Now simply print all parts avail in database.
System.out.println("Sorted part names: ");
for (BicyclePart bicyclePart: bicycleParts){
//same as above but, here only change is that arraylist is sort by it's part number
private static void sortByNumber() {
bicycleParts.sort(new Comparator<BicyclePart>() {
//Compare with part number.
public int compare(BicyclePart o1, BicyclePart o2) {
return Long.compare(o1.id,o2.id);
//Print the sorted arrayList.
System.out.println("Sorted part names: ");
for (BicyclePart bicyclePart: bicycleParts){
private static void saveDatabase() {
//Check databaseUpdated flag.
//If it is false, means no method execute which change the current database.
//Therefore no need to save it.
//return back.
//if it is true. write it to file.
//first write it to temp file.
//then delete the old database file.
//after that rename the temp file to database file.
try {
//Create file output stream to write the data.
FileOutputStream outputStream = new FileOutputStream("temp.txt");
//create buffered writer to write line by line.
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream));
//loop through all part available in array list(database)
for (BicyclePart bicyclePart:bicycleParts){
//write the bicycle part to file follow with a new line.
//bicycle.toString is defined in BicyclePart.java
//which gives whole thing in string with comma seperator.
writer.write(bicyclePart.toString() + "\n");
//close the writer.
//close output stream.
//check if the old database file actually exists or not.
//if exists delete it.
//create a file object with name temp.txt
File file = new File("temp.txt");
//rename it to database file.
}catch (Exception ignore){
//rise error if anything happens wrong.

No comments:

Post a Comment

Bottom Ad [Post Page]

| Designed by Colorlib