Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

File Handling Tasks

Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

DEPARTMENT OF COMPUTER & SOFTWARE ENGINEERING

COLLEGE OF E&ME, NUST, RAWALPINDI

LAB REPORT 14

SUBJECT NAME:

OOP

Lecturer:

Mam Anum

SUBMITTED BY:

NAME: Dur E Haider Hussain Fayyaz


REG NO: 404018
DE-44 (CE)-A
File Handling Tasks
Task 1: Inventory Transaction Management

Objective: Develop a program for managing inventory transactions in a hardware store, including
stock updates, sales, and generating reports.

Instructions:
1. Initialize a file named "inventory.dat" with records for different items in the store. Each record
should include fields for item identification number, item name, current stock quantity, and cost per
unit.

2. Provide a menu-driven interface with the following options:


- Option 1: Update Stock
- Prompt the user to enter the item identification number and the quantity of stock to be added or
removed.
- Update the stock quantity in the "inventory.dat" file accordingly.
- Option 2: Record Sale
- Prompt the user to enter the item identification number and the quantity sold.
- Update the stock quantity and calculate the total sale amount.
- Option 3: Generate Stock Report
- Display a report listing all items in the inventory, including their identification number, name,
current stock quantity, and cost per unit.
- Option 4: Generate Sales Report
- Display a report listing all sales transactions, including item details, quantity sold, and total sale
amount.
- Option 5: Exit
- Terminate the program.

3. Implement proper error handling:


- Validate user input to ensure it meets the required criteria (e.g., numeric values for quantities).
- Ensure that the program handles cases where the user tries to sell more items than are available in
stock.

4. Include features to calculate and update the total revenue earned from sales.
5. Allow the program to continue running until the user chooses to exit.

Sol:
Class main:
package lab14;

import java.io.*;

public class Main {


private static final String filepath =
"C:\\Users\\durha\\OneDrive\\Documents\\output.txt";

public static void main(String[] args) throws IOException{


// Main objectIO = new Main();
FileOutputStream fileOut = new FileOutputStream(filepath);

ObjectOutputStream objectOut = new


ObjectOutputStream(fileOut);
Manager chips = new Manager(3156, "chips", 100, 34.5);
chips.recordSales();
Manager juices = new Manager(2654, "juice", 100, 5);
juices.recordSales();
String objString = chips.toString();
objectOut.writeObject(objString);//writing object to file
objString=juices.toString();
objectOut.writeObject(objString);

objectOut.close();
System.out.println("The Object was successfully written to a
file");

}
}

Class Manager:
package lab14;

import java.io.*;
import java.util.Scanner;

public class Manager implements Serializable {


private static final long serialVersionUID = 1L;
public int ID_num;
public String name;
public int current_stock_quantity;
public double cost_per_unit;
public int total_quantity_sold;
public double total_sales;
transient Scanner obj = new Scanner(System.in);

public Manager(int r, String b, int c, double d) {


ID_num = r;
name = b;
current_stock_quantity = c;
cost_per_unit = d;
}///constructor

public void updateStock(String addedRemoved, int quantity)


{//updating a stock
//with condition and quantity
if (addedRemoved.equals("added")) {
current_stock_quantity += quantity;
System.out.println("Updated quantity: " +
current_stock_quantity);
} else if (addedRemoved.equals("removed")) {
try {//try catc block for exceeding quantity
if (quantity > current_stock_quantity) {
throw new IllegalArgumentException("Cannot remove
more items than available in stock");
} else {
current_stock_quantity -= quantity;
System.out.println("Updated quantity: " +
current_stock_quantity);
}
} catch (IllegalArgumentException ex) {
System.out.println(ex.getMessage());
}
}
}

public void recordSales() {//record of sales


System.out.println("Enter quantity sold");
int s = obj.nextInt();

updateStock("removed", s);//sending quantity and condition


double sales = s * cost_per_unit;

total_quantity_sold += s;
total_sales += sales;
}

public void generateStockReport() {//generating output


System.out.println("ID number: " + ID_num);
System.out.println("Name: " + name);
System.out.println("Current Stock Quantity: " +
current_stock_quantity);
System.out.println("Cost Per Unit: " + cost_per_unit);
}

public void generateSalesReport() {//generating output


System.out.println("Total Sales: " + total_sales);
System.out.println("Total Quantity Sold: " +
total_quantity_sold);
}

@Override
public String toString() {//generating output for file
return "Manager{" +
"ID_num=" + ID_num +
", name='" + name + '\'' +
", current_stock_quantity=" + current_stock_quantity
+
", cost_per_unit=" + cost_per_unit +
", total_quantity_sold=" + total_quantity_sold +
", total_sales=" + total_sales +
'}';
}
}

Output:
On wrong entry

On correct entry
Written into a file:
Task 2 : To-Do List Management

Objective: Create a program to manage a to-do list using a text file. The program should allow users to
add tasks, mark tasks as completed, and display the pending tasks.

Instructions:
1. Initialize a text file named "todo_list.txt" to store the to-do list. Each line in the file should represent
a task with the following format: TaskID,TaskDescription,Status.
- Example: 1,Buy groceries,Incomplete

2. Provide a menu-driven interface with the following options:


- Option 1: Add New Task
- Prompt the user to enter a new task description.
- Assign a unique task ID and set the status to "Incomplete."
- Add the new task to the "todo_list.txt" file.
- Option 2: Mark Task as Completed
- Prompt the user to enter the task ID of the completed task.
- Update the status of the specified task to "Complete" in the "todo_list.txt" file.
- Option 3: Display Pending Tasks
- Display the task IDs and descriptions of all incomplete tasks from the "todo_list.txt" file.
- Option 4: Exit
- Terminate the program.

3. Implement basic error handling:


- Validate user input for task IDs.
- Display appropriate messages if the user attempts to mark a non-existent task as completed.

4. Allow the program to continue running until the user chooses to exit.

Sol:
Class todolist:
package lab14tsk2;

import java.util.Scanner;

public class Todolist {


private int Task_ID;
private String Status;
private String Task_description;
Scanner obj = new Scanner(System.in);

public Todolist() {
}

public void add_new_task() {


System.out.println("Enter Task_ID:");
Task_ID = obj.nextInt();
obj.nextLine(); // Consume the newline character
System.out.println("Enter task's description:");
Task_description = obj.nextLine();
Status = "Incomplete";
}

public void task_completed() {


Status = "Completed";
}

public int get_ID() {


return Task_ID;
}

public String toString() {


System.out.println();
return " Task ID: " + Task_ID + "" +
" Status " + Status + " Task_description
" + Task_description;

}
}

Class main:
package lab14tsk2;

import java.io.*;
import java.util.InputMismatchException;
import java.util.Scanner;

public class Main {


static int i = 0;
static int input;
private static int size = 5;
static Todolist[] task;
private static final String path =
"C:\\Users\\durha\\OneDrive\\Documents\\out.txt";

public static void main(String[] args) throws IOException,


ClassNotFoundException {
Scanner obj = new Scanner(System.in);
task = new Todolist[size];
FileOutputStream output = new FileOutputStream(path);
ObjectOutputStream Objectout = new
ObjectOutputStream(output);
FileInputStream infile = new FileInputStream(path);
ObjectInputStream objectin = new ObjectInputStream(infile);

do {
System.out.println("Enter input respectively:" +
"1: for adding a new task " +
"2: for marking task as completed" +
"3: for displaying pending tasks" +
"-1: to exit ");
try {
input = obj.nextInt();

switch (input) {
case 1: {//case for adding task
task[i] = new Todolist();
task[i].add_new_task();
String s = task[i].toString();
Objectout.writeObject(s);
System.out.println();
i++;
break;
}
case 2: {//case for marking complete
System.out.println("Enter input for marking a
specific task completed");
int current_ID = obj.nextInt();

for (int j = 0; j < size; j++) {//iterating


through whole size to find entered ID
if (task[j] != null && current_ID ==
task[j].get_ID()) {
task[j].task_completed();
String ps = task[j].toString();
Objectout.writeObject(ps);
System.out.println();
break;
} else if (task[j] != null && current_ID
!= task[j].get_ID()) {
continue;
} else {
System.out.println("no ID with the
similarity found");
}
}
break;
}
case 3: {//reading from file
System.out.println("reading into a file");
objectin.readObject();
System.out.println();
break;
}
}
} catch (InputMismatchException ex) {//incorrect type
enetered
System.out.println("incorrect type entered");
System.out.println(ex);
obj.next(); // consume the invalid input
}
} while (input != -1);//keep iterating till input ==-1
}
}

Output:
Written into a file:

Conclusion:
In current lab we handled exceptions i.e. input mismatch and illegal argument and how to write into a
file or get it from the file.

You might also like