CMP202 test Q3 Solution
TEXT FILE
1001,Infinix,x600,2015
1003,Infinix,x551,2017
1002,Infinix,x601,2016
1005,Sony,XPeria,2009
1006,Galaxy,s7,2008
1007,Gionee,Tab,2017
1010,Tecno,CX,2019
ENTITY CLASS
package Product;
import java.util.*;
public class ProductRecord implements Comparable <ProductRecord> {
int pId;
String pName;
String pModel;
int pYear;
public ProductRecord(int pId, String pName, String pModel, int pYear) {
this.pId = pId;
this.pName = pName;
this.pModel = pModel;
this.pYear = pYear;
}
public String toString(){
return pId + "," + pName + "," + pModel + "," + pYear;
}
// ThIS WILL HELP TO SORT THE RECORD IN DESCENDING ORDER
public int compareTo(ProductRecord record){
int var = record.pId - this.pId;
if(var > 0){
return 1;
} else if(var < 0) {
return-1;
} else {
return 0;
}
}
}
MAIN CLASS
package Product;
import java.util.*;
import java.io.*;
public class Products {
static int pId,
pYear;
static String pName,
pModel;
static Scanner input = null;
public static void main(String[] args) {
ArrayList<ProductRecord> products = new ArrayList<ProductRecord>();
try{
//READING FROM A FILE
File file = new File("records.txt");
FileReader inputStream = new FileReader(file);
BufferedReader inputBuffer = new BufferedReader(inputStream);
input = new Scanner(inputBuffer);
while(input.hasNextLine()){
String line = input.nextLine();
pId = Integer.parseInt(line.split(",")[0]);
pName = line.split(",")[1];
pModel = line.split(",")[2];
pYear = Integer.parseInt(line.split(",")[3]);
products.add(new ProductRecord(pId,pName,pModel,pYear));
}
if(!file.exists()){
file.createNewFile();
}
//3b: SAVE A NEW RECORD TO THE FILE
FileWriter outputStream = new FileWriter(file, true);
BufferedWriter outputBuffer = new BufferedWriter(outputStream);
PrintWriter outputPrinter = new PrintWriter(outputBuffer);
input = new Scanner(System.in);
for(int x = 0; x < 1; x++){
System.out.print("Enter Product ID: ");
pId = input.nextInt();
System.out.print("Enter Product Name: ");
pName = input.next();
System.out.print("Enter Product Model: ");
pModel = input.next();
System.out.print("Enter Product Year: ");
pYear = input.nextInt();
//Add To the File
outputPrinter.print("");
outputPrinter.println(pId+", "+pName+", "+pModel+", "+pYear);
products.add(new ProductRecord(pId,pName,pModel,pYear));
}
//Close the streams
outputPrinter.flush();
outputPrinter.close();
//3a: SORTING THE RECORDS IN DESCENDING ORDER
Collections.sort(products);
//3c: DISPLAY RECORD
int serial_num = 0;
for(ProductRecord p: products){
num++;
System.out.println(serial_num + " - " + p);
}
}catch(IOException error){
System.out.println(error.getMessage());
}
}
}
Comments
Post a Comment