SlideShare a Scribd company logo
1 of 9
Download to read offline
Using Array Approach, Linked List approach, and Delete Byte Approach: (add code for all three
approaches) (different classes preffered)
I am adding the sample program that you can use and modify, and add code to it.
You need to create a program that reads the input file (items.txt), and store the items in the file in
the Item array as well as the Array List. After creating that array, send the output records from
the file to a new file "ex1out1.txt"
Now, according to "p2changes.txt", you need to add or delete the record specified ( A or a: add
D or d: delete)
items.txt:
items.txt:
p2changes.txt:
A, 106,ChainSaw 12"
D,102
d,104
a,107,ChainSaw 10"
Sample program: (Sample program does input output files and array outputting which is
required)
Main:
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main {
private static void step1() {
// Creating an array and an array list itemArray and itemArrayList
List itemArray = new ArrayList<>(10);
List itemArrayList = new ArrayList<>();
try {
//reading from file "items.txt"
BufferedReader reader = new BufferedReader(new InputStreamReader(new
FileInputStream("C:/Users/patel/Desktop/items.txt")));
String line = reader.readLine();
while (line != null) {
//splitting file by comma
String[] array = line.split(",");
Item item = new Item(Integer.parseInt(array[0]),array[1]);
itemArray.add(item);
itemArrayList.add(item);
line = reader.readLine();
}
//opening file for output
PrintWriter writer = new PrintWriter("C:/Users/patel/Desktop/ex1out1.txt");
writer.println("Aashiv " + " Patel");
//sorting in reverse order
Collections.sort(itemArray, new Comparator() {
@Override
public int compare(Item o1, Item o2) {
return o2.getItemNumber() - o1.getItemNumber();
}
});
// moving through the ArrayList and printing the items
writer.println();
writer.print("Array Format: ");
writer.println();
for(Item item : itemArray) {
writer.println();
writer.println(item);
}
//sorting in sequential order of numbers
Collections.sort(itemArrayList, new Comparator() {
@Override
public int compare(Item item1, Item item2) {
return item1.getItemNumber() - item2.getItemNumber();
}
});
// moving through the ArrayList and printing the items
writer.println();
writer.print("Array List Format: ");
writer.println();
for(Item item : itemArrayList) {
writer.println();
writer.println(item);
}
//closing both writers and readers
writer.close();
reader.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
// Main method to call the step1 method
public static void main(String args[]) {
step1();
}
}
Item.java:
public class Item {
private int itemNumber; //number of item
private String itemName; //name of item
Item(int number, String name)
{
this.itemNumber = number;
this.itemName = name;
}
//return the artistName
public String getItemName() {
return itemName;
}
//set the artistName
public void set(int itemNumber, String itemName) {
this.itemName = itemName;
this.itemNumber = itemNumber;
}
//return the artistId
public int getItemNumber() {
return itemNumber;
}
// toString method
public String toString() {
return this.itemNumber + "," + this.itemName;
}
}
Solution
//In this code all changes from p2changes.txt file are made on ex1out1.txt and ex1out2.txt files.
//Item.txt file contains original contents.
import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
public class Main
{
private static List itemArray = new ArrayList<>(10);
private static List itemArrayList = new ArrayList<>();
private static void writeFile()
{
//opening file for output
try
{
PrintWriter writer = new PrintWriter("./ex1out1.txt");
PrintWriter writer2=new PrintWriter("./ex1out2.txt");
//sorting in reverse order
Collections.sort(itemArray, new Comparator()
{
@Override
public int compare(Item o1, Item o2)
{
return o2.getItemNumber() - o1.getItemNumber();
}
});
writer.println("Array Format :");
System.out.println("Array Format :");
for(Item item : itemArray)
{
System.out.println(item);
writer.println(item);
}
//sorting in sequential order of numbers
Collections.sort(itemArrayList, new Comparator()
{
@Override
public int compare(Item item1, Item item2)
{
return item1.getItemNumber() - item2.getItemNumber();
}
});
// moving through the ArrayList and printing the items
writer2.println("Array List Format: ");
System.out.println("Array List Format:");
for(Item item : itemArrayList)
{
System.out.println(item);
writer2.println(item);
}
//closing both writers and readers
writer.close();
writer2.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
private static void step1()
{
// Creating an array and an array list itemArray and itemArrayList
try
{
//reading from file "items.txt"
BufferedReader reader = new BufferedReader(new InputStreamReader(new
FileInputStream("./items.txt")));
String line = reader.readLine();
while (line != null)
{
//splitting file by comma
String[] array = line.split(",");
Item item = new Item(Integer.parseInt(array[0]),array[1]);
itemArray.add(item);
itemArrayList.add(item);
line = reader.readLine();
}
System.out.println("Before making changes content of files ex1out1 and ext1out2
files");
writeFile();
System.out.println("==============");
reader.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
public static void step2()
{
try
{
BufferedReader reader = new BufferedReader(new InputStreamReader(new
FileInputStream("./p2changes.txt")));
String line = reader.readLine();
while (line != null)
{
//splitting file by comma
String[] array = line.split(",");
//checking the string of whether it is for adding new item or deleting an item
if(array[0].equals("A") || array[0].equals("a"))
{
Item item = new Item(Integer.parseInt(array[1]),array[2]);
itemArray.add(item);
itemArrayList.add(item);
}
else if(array[0].equals("D") || array[0].equals("d"))
{
//iterating through array for finding an item to delete
for(Item item : itemArray)
{
if(item.getItemNumber()==Integer.parseInt(array[1]))
{
itemArray.remove(item);
itemArrayList.remove(item);
break;
}
}
}
line = reader.readLine();
}
System.out.println("After making changes as in file p2changes.txt ====");
writeFile();
reader.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
// Main method to call the step1 method
public static void main(String args[])
{
step1();
step2();
}
}
//ex1out2.txt
Array List Format:
101,Nail #1
103,Nail #3
105,Hammer Large
106,ChainSaw 12"
107,ChainSaw 10"
//ex1out1.txt
Array Format :
107,ChainSaw 10"
106,ChainSaw 12"
105,Hammer Large
103,Nail #3
101,Nail #1
//p2changes.txt
A,106,ChainSaw 12"
D,102
d,104
a,107,ChainSaw 10"
//item.txt
101,Nail #1
102,Nail #2
103,Nail #3
104,Hammer Small
105,Hammer Large

More Related Content

Similar to Using Array Approach, Linked List approach, and Delete Byte Approach.pdf

-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
ganisyedtrd
 
BackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfBackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdf
mayorothenguyenhob69
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdf
admin463580
 
please follow all instructions and answer the inbedded questions- and.pdf
please follow all instructions and answer the inbedded questions- and.pdfplease follow all instructions and answer the inbedded questions- and.pdf
please follow all instructions and answer the inbedded questions- and.pdf
Ian5L3Allanm
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdf
aromalcom
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
info309708
 
This is a java lab assignment. I have added the first part java re.pdf
This is a java lab assignment. I have added the first part java re.pdfThis is a java lab assignment. I have added the first part java re.pdf
This is a java lab assignment. I have added the first part java re.pdf
feetshoemart
 
written in c- please answer the 4 questions and write the functions ba.pdf
written in c- please answer the 4 questions and write the functions ba.pdfwritten in c- please answer the 4 questions and write the functions ba.pdf
written in c- please answer the 4 questions and write the functions ba.pdf
sravi07
 
Write a function which return a list of all of the n element subset .pdf
Write a function which return a list of all of the n element subset .pdfWrite a function which return a list of all of the n element subset .pdf
Write a function which return a list of all of the n element subset .pdf
hardjasonoco14599
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
secunderbadtirumalgi
 
Sorted number list implementation with linked listsStep 1 Inspec.pdf
 Sorted number list implementation with linked listsStep 1 Inspec.pdf Sorted number list implementation with linked listsStep 1 Inspec.pdf
Sorted number list implementation with linked listsStep 1 Inspec.pdf
almaniaeyewear
 
Stack linked list
Stack linked listStack linked list
Stack linked list
bhargav0077
 
Written in C- requires linked lists- Please answer the 4 questions and.pdf
Written in C- requires linked lists- Please answer the 4 questions and.pdfWritten in C- requires linked lists- Please answer the 4 questions and.pdf
Written in C- requires linked lists- Please answer the 4 questions and.pdf
sravi07
 
Written in C- requires linked lists- Please answer the 4 questions and (1).pdf
Written in C- requires linked lists- Please answer the 4 questions and (1).pdfWritten in C- requires linked lists- Please answer the 4 questions and (1).pdf
Written in C- requires linked lists- Please answer the 4 questions and (1).pdf
sravi07
 

Similar to Using Array Approach, Linked List approach, and Delete Byte Approach.pdf (20)

-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
-- Write the compiler used- Visual studio or gcc -- Reminder that your.pdf
 
Basic data-structures-v.1.1
Basic data-structures-v.1.1Basic data-structures-v.1.1
Basic data-structures-v.1.1
 
BackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdfBackgroundIn many applications, the composition of a collection o.pdf
BackgroundIn many applications, the composition of a collection o.pdf
 
Collections
CollectionsCollections
Collections
 
Please the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdfPlease the following is the currency class of perious one- class Curre.pdf
Please the following is the currency class of perious one- class Curre.pdf
 
please follow all instructions and answer the inbedded questions- and.pdf
please follow all instructions and answer the inbedded questions- and.pdfplease follow all instructions and answer the inbedded questions- and.pdf
please follow all instructions and answer the inbedded questions- and.pdf
 
LectureNotes-06-DSA
LectureNotes-06-DSALectureNotes-06-DSA
LectureNotes-06-DSA
 
In java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdfIn java , I want you to implement a Data Structure known as a Doubly.pdf
In java , I want you to implement a Data Structure known as a Doubly.pdf
 
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdfGetting StartedCreate a class called Lab8. Use the same setup for .pdf
Getting StartedCreate a class called Lab8. Use the same setup for .pdf
 
This is a java lab assignment. I have added the first part java re.pdf
This is a java lab assignment. I have added the first part java re.pdfThis is a java lab assignment. I have added the first part java re.pdf
This is a java lab assignment. I have added the first part java re.pdf
 
Introduction to objects and inputoutput
Introduction to objects and inputoutput Introduction to objects and inputoutput
Introduction to objects and inputoutput
 
written in c- please answer the 4 questions and write the functions ba.pdf
written in c- please answer the 4 questions and write the functions ba.pdfwritten in c- please answer the 4 questions and write the functions ba.pdf
written in c- please answer the 4 questions and write the functions ba.pdf
 
Write a function which return a list of all of the n element subset .pdf
Write a function which return a list of all of the n element subset .pdfWrite a function which return a list of all of the n element subset .pdf
Write a function which return a list of all of the n element subset .pdf
 
(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual(674335607) cs2309 java-lab-manual
(674335607) cs2309 java-lab-manual
 
Change the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdfChange the code in Writer.java only to get it working. Must contain .pdf
Change the code in Writer.java only to get it working. Must contain .pdf
 
Sorted number list implementation with linked listsStep 1 Inspec.pdf
 Sorted number list implementation with linked listsStep 1 Inspec.pdf Sorted number list implementation with linked listsStep 1 Inspec.pdf
Sorted number list implementation with linked listsStep 1 Inspec.pdf
 
Stack linked list
Stack linked listStack linked list
Stack linked list
 
Collection and framework
Collection and frameworkCollection and framework
Collection and framework
 
Written in C- requires linked lists- Please answer the 4 questions and.pdf
Written in C- requires linked lists- Please answer the 4 questions and.pdfWritten in C- requires linked lists- Please answer the 4 questions and.pdf
Written in C- requires linked lists- Please answer the 4 questions and.pdf
 
Written in C- requires linked lists- Please answer the 4 questions and (1).pdf
Written in C- requires linked lists- Please answer the 4 questions and (1).pdfWritten in C- requires linked lists- Please answer the 4 questions and (1).pdf
Written in C- requires linked lists- Please answer the 4 questions and (1).pdf
 

More from fms12345

Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdfExercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
fms12345
 
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdfCHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
fms12345
 
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdfCompany names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
fms12345
 
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
fms12345
 
What specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdfWhat specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdf
fms12345
 
What are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdfWhat are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdf
fms12345
 
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdfTV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
fms12345
 
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdfTim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
fms12345
 

More from fms12345 (20)

Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdfExercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
Exercise 1 (10 Points) Define a FixdLenStringList class that encaps.pdf
 
Describe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdfDescribe the procedure you would use in the laboratory to determine .pdf
Describe the procedure you would use in the laboratory to determine .pdf
 
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdfCHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
CHEM 1011 Discussion question 2ObjectiveTo learn more about the .pdf
 
Could you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdfCould you implement this please. I was told to use pointers as the d.pdf
Could you implement this please. I was told to use pointers as the d.pdf
 
A piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdfA piece of malware is running on a Windows 7 machine via process inj.pdf
A piece of malware is running on a Windows 7 machine via process inj.pdf
 
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdfCompany names Aerial Drones Surveillance Inc. Your company descript.pdf
Company names Aerial Drones Surveillance Inc. Your company descript.pdf
 
2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf2. The Lorenz curve measures inequality in person income distribution.pdf
2. The Lorenz curve measures inequality in person income distribution.pdf
 
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf13 808 PM  docs.google.com Covalent Bonding and lonic Bonding study.pdf
13 808 PM docs.google.com Covalent Bonding and lonic Bonding study.pdf
 
1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf1.The shrimping industry needs female shrimp for production purposes.pdf
1.The shrimping industry needs female shrimp for production purposes.pdf
 
Who are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdfWho are the stakeholders in an income statement and whySolution.pdf
Who are the stakeholders in an income statement and whySolution.pdf
 
Which company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdfWhich company maintains natural habitats while B allowing us to live .pdf
Which company maintains natural habitats while B allowing us to live .pdf
 
When multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdfWhen multiple strains of the same bacterial species are sequenced, w.pdf
When multiple strains of the same bacterial species are sequenced, w.pdf
 
What specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdfWhat specialized cells line the inner cavity and move fluids through.pdf
What specialized cells line the inner cavity and move fluids through.pdf
 
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdfWhat does the metaphor meaning for the Iron curtainSolutionIr.pdf
What does the metaphor meaning for the Iron curtainSolutionIr.pdf
 
What are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdfWhat are the major developmental milestones between infancy and todd.pdf
What are the major developmental milestones between infancy and todd.pdf
 
Using the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdfUsing the Web or another research tool, search for alternative means.pdf
Using the Web or another research tool, search for alternative means.pdf
 
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdfTV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
TV Guide magazine ran a cover photo for a story emphasizing Oprah Wi.pdf
 
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdfTim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
Tim Tassopoulos, the chief operating officer for Chick-Fll-A applies .pdf
 
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdfThe Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
The Hydrolysis of the Hydrated Pb ion PboH (aq) + H200SolutionP.pdf
 
1. CDOs are normally divided into tranches. Holders of this tranche .pdf
1. CDOs are normally divided into tranches. Holders of this tranche .pdf1. CDOs are normally divided into tranches. Holders of this tranche .pdf
1. CDOs are normally divided into tranches. Holders of this tranche .pdf
 

Recently uploaded

Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 

Recently uploaded (20)

Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Single or Multiple melodic lines structure
Single or Multiple melodic lines structureSingle or Multiple melodic lines structure
Single or Multiple melodic lines structure
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
SOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning PresentationSOC 101 Demonstration of Learning Presentation
SOC 101 Demonstration of Learning Presentation
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Fostering Friendships - Enhancing Social Bonds in the Classroom
Fostering Friendships - Enhancing Social Bonds  in the ClassroomFostering Friendships - Enhancing Social Bonds  in the Classroom
Fostering Friendships - Enhancing Social Bonds in the Classroom
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Micro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdfMicro-Scholarship, What it is, How can it help me.pdf
Micro-Scholarship, What it is, How can it help me.pdf
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
Plant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptxPlant propagation: Sexual and Asexual propapagation.pptx
Plant propagation: Sexual and Asexual propapagation.pptx
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
Key note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdfKey note speaker Neum_Admir Softic_ENG.pdf
Key note speaker Neum_Admir Softic_ENG.pdf
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Food safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdfFood safety_Challenges food safety laboratories_.pdf
Food safety_Challenges food safety laboratories_.pdf
 

Using Array Approach, Linked List approach, and Delete Byte Approach.pdf

  • 1. Using Array Approach, Linked List approach, and Delete Byte Approach: (add code for all three approaches) (different classes preffered) I am adding the sample program that you can use and modify, and add code to it. You need to create a program that reads the input file (items.txt), and store the items in the file in the Item array as well as the Array List. After creating that array, send the output records from the file to a new file "ex1out1.txt" Now, according to "p2changes.txt", you need to add or delete the record specified ( A or a: add D or d: delete) items.txt: items.txt: p2changes.txt: A, 106,ChainSaw 12" D,102 d,104 a,107,ChainSaw 10" Sample program: (Sample program does input output files and array outputting which is required) Main: import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class Main { private static void step1() { // Creating an array and an array list itemArray and itemArrayList List itemArray = new ArrayList<>(10); List itemArrayList = new ArrayList<>(); try { //reading from file "items.txt" BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("C:/Users/patel/Desktop/items.txt"))); String line = reader.readLine();
  • 2. while (line != null) { //splitting file by comma String[] array = line.split(","); Item item = new Item(Integer.parseInt(array[0]),array[1]); itemArray.add(item); itemArrayList.add(item); line = reader.readLine(); } //opening file for output PrintWriter writer = new PrintWriter("C:/Users/patel/Desktop/ex1out1.txt"); writer.println("Aashiv " + " Patel"); //sorting in reverse order Collections.sort(itemArray, new Comparator() { @Override public int compare(Item o1, Item o2) { return o2.getItemNumber() - o1.getItemNumber(); } }); // moving through the ArrayList and printing the items writer.println(); writer.print("Array Format: "); writer.println(); for(Item item : itemArray) { writer.println(); writer.println(item); } //sorting in sequential order of numbers Collections.sort(itemArrayList, new Comparator() { @Override public int compare(Item item1, Item item2) { return item1.getItemNumber() - item2.getItemNumber(); }
  • 3. }); // moving through the ArrayList and printing the items writer.println(); writer.print("Array List Format: "); writer.println(); for(Item item : itemArrayList) { writer.println(); writer.println(item); } //closing both writers and readers writer.close(); reader.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } // Main method to call the step1 method public static void main(String args[]) { step1(); } } Item.java: public class Item { private int itemNumber; //number of item private String itemName; //name of item Item(int number, String name) { this.itemNumber = number; this.itemName = name; }
  • 4. //return the artistName public String getItemName() { return itemName; } //set the artistName public void set(int itemNumber, String itemName) { this.itemName = itemName; this.itemNumber = itemNumber; } //return the artistId public int getItemNumber() { return itemNumber; } // toString method public String toString() { return this.itemNumber + "," + this.itemName; } } Solution //In this code all changes from p2changes.txt file are made on ex1out1.txt and ex1out2.txt files. //Item.txt file contains original contents. import java.io.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Scanner; public class Main { private static List itemArray = new ArrayList<>(10); private static List itemArrayList = new ArrayList<>(); private static void writeFile() { //opening file for output
  • 5. try { PrintWriter writer = new PrintWriter("./ex1out1.txt"); PrintWriter writer2=new PrintWriter("./ex1out2.txt"); //sorting in reverse order Collections.sort(itemArray, new Comparator() { @Override public int compare(Item o1, Item o2) { return o2.getItemNumber() - o1.getItemNumber(); } }); writer.println("Array Format :"); System.out.println("Array Format :"); for(Item item : itemArray) { System.out.println(item); writer.println(item); } //sorting in sequential order of numbers Collections.sort(itemArrayList, new Comparator() { @Override public int compare(Item item1, Item item2) { return item1.getItemNumber() - item2.getItemNumber(); } }); // moving through the ArrayList and printing the items writer2.println("Array List Format: "); System.out.println("Array List Format:"); for(Item item : itemArrayList) { System.out.println(item); writer2.println(item);
  • 6. } //closing both writers and readers writer.close(); writer2.close(); } catch(Exception e) { e.printStackTrace(); } } private static void step1() { // Creating an array and an array list itemArray and itemArrayList try { //reading from file "items.txt" BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("./items.txt"))); String line = reader.readLine(); while (line != null) { //splitting file by comma String[] array = line.split(","); Item item = new Item(Integer.parseInt(array[0]),array[1]); itemArray.add(item); itemArrayList.add(item); line = reader.readLine(); } System.out.println("Before making changes content of files ex1out1 and ext1out2 files"); writeFile(); System.out.println("=============="); reader.close(); } catch (FileNotFoundException e) {
  • 7. e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } public static void step2() { try { BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream("./p2changes.txt"))); String line = reader.readLine(); while (line != null) { //splitting file by comma String[] array = line.split(","); //checking the string of whether it is for adding new item or deleting an item if(array[0].equals("A") || array[0].equals("a")) { Item item = new Item(Integer.parseInt(array[1]),array[2]); itemArray.add(item); itemArrayList.add(item); } else if(array[0].equals("D") || array[0].equals("d")) { //iterating through array for finding an item to delete for(Item item : itemArray) { if(item.getItemNumber()==Integer.parseInt(array[1])) { itemArray.remove(item); itemArrayList.remove(item); break; }
  • 8. } } line = reader.readLine(); } System.out.println("After making changes as in file p2changes.txt ===="); writeFile(); reader.close(); } catch(Exception e) { e.printStackTrace(); } } // Main method to call the step1 method public static void main(String args[]) { step1(); step2(); } } //ex1out2.txt Array List Format: 101,Nail #1 103,Nail #3 105,Hammer Large 106,ChainSaw 12" 107,ChainSaw 10" //ex1out1.txt Array Format : 107,ChainSaw 10" 106,ChainSaw 12" 105,Hammer Large 103,Nail #3 101,Nail #1 //p2changes.txt
  • 9. A,106,ChainSaw 12" D,102 d,104 a,107,ChainSaw 10" //item.txt 101,Nail #1 102,Nail #2 103,Nail #3 104,Hammer Small 105,Hammer Large