In: Computer Science
How to read a text file and store the elements into a linked list in java?
Example of a text file:
CS100, Intro to CS, John Smith, 37, 100.00
CS200, Java Programming, Susan Smith, 35, 200.00
CS300, Data Structures, Ahmed Suad, 41, 150.50
CS400, Analysis of Algorithms, Yapsiong Chen, 70, 220.50
and print them out in this format:
Course: CS100
Title: Intro to CS Author:
Name = John Smith,
Age = 37
Price: 100.0.
And also to print out the Most expensive/cheapest book and the Average price.
import java.util.*;
import java.lang.*;
import java.io.*;
class Solution
{
public static void main (String[] args) throws
java.lang.Exception
{
String content = new
String();
int count=1;
File file = new File("abc.txt"); //file name
LinkedList<String> list = new LinkedList<String>(); //
declare link list
try {
Scanner sc = new Scanner(new FileInputStream(file)); // file
input
while (sc.hasNextLine()){
content = sc.nextLine();
list.add(content);
}
sc.close();
}
catch(FileNotFoundException fnf){
fnf.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
System.out.println("Program terminated Safely...");
}
TreeMap<Double, String> price = new TreeMap<>(); //
tree map to get expensive and cheapest book name
Double sum = 0;
Iterator i = list.iterator();
while (i.hasNext()) {
String[] arrOfStr = ((String)i.next()).split(",", 5);
System.out.println("Course: " +arrOfStr[0]);
System.out.println("Title: " +arrOfStr[1]);
System.out.println("Name: " +arrOfStr[2]);
System.out.println("Age: " +arrOfStr[3]);
System.out.println("Price: " +arrOfStr[4]);
price.put(Double.parseDouble(arrOfStr[4]),arrOfStr[1]);
sum = sum + Double.parseDouble(arrOfStr[4]);
}
double average = sum/(double)price.size(); //calculation of average
price
System.out.println("Most Expensive Book Is: " +
price.get(price.lastKey()));
System.out.println("Cheapest Book Is: " +
price.get(price.firstKey()));
System.out.println("Average Price Is: " + average);
}
}
input file
output: