salercode

Zad1Lab1

Mar 5th, 2018
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 12.65 KB | None | 0 0
  1. /*Задача 1 Problem 1 (1 / 1)
  2. Да се напише Java програма која ќе прикаже колкава е просечната големина на датотеките со екстензија .txt во именик зададен како аргумент на командна линија.
  3.  
  4. Напомена: Користете ја File класата за пристап до содржината на именикот.
  5.  
  6. Решение: Решението од HW01_1.java фајлот го поставувате тука со copy-paste*/
  7.  
  8.  
  9. import java.io.File;
  10. import java.io.FilenameFilter;
  11.  
  12. public class HW01_1 {
  13.    
  14.     public static void main(String[] args)  {
  15.        
  16.         if (args.length == 0)
  17.             throw new NoFileException("No file!");
  18.        
  19.         int txtFiles;
  20.         double txtFilesSize;
  21.                
  22.         File directory = new File(args[0]);
  23.        
  24.         if (!directory.isDirectory())
  25.             throw new NotDirectoryException(directory);
  26.        
  27.         FilenameFilter filter = new TxtFilter();
  28.         txtFiles = txtFiles(directory,filter);
  29.         txtFilesSize = txtFilesSize(directory,filter);
  30.         System.out.printf("The average size of the files with .txt extension is %.2fB\n",txtFilesSize / txtFiles);
  31.        
  32.     }
  33.  
  34.     static int txtFiles(File directory,FilenameFilter filter) {
  35.    
  36.         int txtFiles = 0;
  37.         File [] files = directory.listFiles(filter);
  38.        
  39.         for (File contentFile : files) {
  40.             if (contentFile.isDirectory())
  41.                 txtFiles += txtFiles(contentFile,filter);
  42.             else
  43.                 ++txtFiles;
  44.            
  45.         }
  46.  
  47.         return txtFiles;
  48.     }
  49.    
  50.     static double txtFilesSize(File directory,FilenameFilter filter) {
  51.        
  52.         double length = 0;
  53.        
  54.         File [] files = directory.listFiles(filter);
  55.        
  56.         for (File contentFile : files) {
  57.             if (contentFile.isDirectory())
  58.                 length += txtFilesSize(contentFile,filter);
  59.             else
  60.                 length += contentFile.length();
  61.         }
  62.        
  63.         return length;
  64.        
  65.     }
  66.    
  67. }
  68.  
  69. class TxtFilter implements FilenameFilter {
  70.    
  71.     @Override
  72.     public boolean accept(File dir, String name) {
  73.         File file = new File(dir,name);
  74.        
  75.         return file.isDirectory() ||
  76.                 file.isFile()&&name.endsWith(".txt");
  77.    
  78.     }
  79. }
  80.  
  81. class NoFileException extends RuntimeException {
  82.    
  83.     public NoFileException(String message) {
  84.         super(message);
  85.     }
  86. }
  87.  
  88. class NotDirectoryException extends RuntimeException {
  89.    
  90.     public NotDirectoryException(File file) {
  91.         super(String.format("File %s is not a directory!", file.getName()));
  92.     }
  93.    
  94. }
  95. /*Задача 2 Problem 2 (1 / 1)
  96. Да се напише Java програма која со користење на I/O стримови ќе ја прочита содржината на датотеката izvor.txt, а потоа нејзината содржина ќе ја испише превртена во празната датотека destinacija.txt. Читањето и запишувањето реализирајте го со стримови кои работат бајт по бајт.
  97.  
  98. Пример:
  99.  
  100. izvor.txt                   destinacija.txt
  101.  
  102. Оперативни системи          иметсис инвитарепО
  103. Напомена: Сами креирајте ги овие две датотеки и пополнете ја izvor.txt со произволна содржина.
  104.  
  105. Решение: Решението од HW01_2.java фајлот го поставувате тука со copy-paste*/
  106.  
  107.  
  108. import java.io.File;
  109. import java.io.FileWriter;
  110. import java.io.IOException;
  111. import java.io.RandomAccessFile;
  112.  
  113. public class HW01_2 {
  114.    
  115.     static String SOURCE = "izvor.txt";
  116.     static String DESTINATION = "destinacija.txt";
  117.    
  118.     public static void main(String[] args) throws IOException {
  119.        
  120.        
  121.         RandomAccessFile sourceFile = null;
  122.         FileWriter destinationFile = null;
  123.        
  124.         try {
  125.         sourceFile = new RandomAccessFile(SOURCE, "r");
  126.         destinationFile = new FileWriter(new File(DESTINATION));
  127.        
  128.         reverse(sourceFile,destinationFile);
  129.        
  130.         }
  131.         finally {
  132.             if (sourceFile != null)
  133.                 sourceFile.close();
  134.             if (destinationFile != null)
  135.                 destinationFile.close();
  136.         }
  137.        
  138.     }
  139.    
  140.     static void reverse(RandomAccessFile src, FileWriter dest ) throws IOException {
  141.        
  142.         long filePointer = src.length() - 1;
  143.         byte b;
  144.        
  145.         try {
  146.             while (filePointer > -1) {
  147.                
  148.                 src.seek(filePointer);
  149.                 b = src.readByte();
  150.                 dest.write(b);
  151.                 --filePointer;
  152.             }
  153.         }
  154.         finally {}
  155.        
  156.     }
  157.  
  158. }
  159. /*Задача 3 Problem 3 (2 / 2)
  160. Да се напише Java програма која со користење на I/O стримови ќе ја прочита содржината на датотеката izvor.txt, а потоа нејзината содржина ќе ја испише превртена во празната датотека destinacija.txt. Читањето и запишувањето реализирајте го со баферирано читање и запишување Пример:
  161.  
  162. izvor.txt                   destinacija.txt
  163.  
  164. Оперативни системи          иметсис инвитарепО
  165. Напомена: Сами креирајте ги овие две датотеки и пополнете ја izvor.txt со произволна содржина.
  166.  
  167. Решение: Решението од HW01_3.java фајлот го поставувате тука со copy-paste*/
  168.  
  169. import java.util.List;
  170. import java.io.BufferedReader;
  171. import java.io.BufferedWriter;
  172. import java.io.FileReader;
  173. import java.io.FileWriter;
  174. import java.io.IOException;
  175. import java.util.ArrayList;
  176.  
  177. public class HW01_3 {
  178.    
  179.    
  180.     static String SOURCE = "izvor.txt";
  181.     static String DESTINATION = "destination.txt";
  182.  
  183.     public static void main(String[] args) throws IOException {
  184.        
  185.         BufferedReader reader = null;
  186.         BufferedWriter writer = null;
  187.        
  188.        
  189.         try {
  190.             reader = new BufferedReader(new FileReader(SOURCE));
  191.             writer = new BufferedWriter(new FileWriter(DESTINATION));
  192.             String line;
  193.             List<String> rows = new ArrayList<>();
  194.             while ((line = reader.readLine()) != null) {
  195.                 rows.add(line);
  196.             }
  197.             reverse(rows,writer);
  198.         }
  199.         finally {
  200.             if (reader != null) reader.close();
  201.             if (writer != null) writer.close();
  202.         }
  203.        
  204.     }
  205.    
  206.     static void reverse(List<String> list, BufferedWriter writer) throws IOException {
  207.  
  208.         int offset = list.size()-1;
  209.         String line;
  210.        
  211.         while (offset >= 0) {
  212.             line = list.get(offset);
  213.             StringBuilder sb = new StringBuilder(line).reverse();
  214.             writer.write(sb.toString());
  215.             writer.newLine();
  216.             --offset;
  217.         }
  218.        
  219.        
  220.     }
  221.    
  222. }
  223. /*Задача 4 Problem 4 (1 / 1)
  224. Да се напише Java програма која прима два аргументи: локација на текстуална датотека и збор. Програмата треба да испечати колку пати се сретнува зборот проследен како втор аргумент, во текстуалната датотека проследена како прв аргумент.
  225.  
  226. Решение: Решението од HW01_4.java фајлот го поставувате тука со copy-paste*/
  227.  
  228.  
  229. import java.io.File;
  230. import java.io.FileInputStream;
  231. import java.io.FileNotFoundException;
  232.  
  233. import java.util.Scanner;
  234.  
  235. public class HW01_4 {
  236.  
  237.     public static void main(String[] args) throws FileNotFoundException {
  238.        
  239.         if (args.length != 2) {
  240.             System.out.println("The number of the arguments is not valid.");
  241.             System.exit(-1);
  242.         }
  243.        
  244.         String filePath = args[0];
  245.         String word = args[1];
  246.        
  247.         File file = new File(filePath);
  248.        
  249.         int counter = numberOfWord(file,word);
  250.         System.out.printf("The word %s appears %d times in the file %s",word,counter,file.getName());
  251.        
  252.     }
  253.    
  254.     static int numberOfWord(File file, String word) throws FileNotFoundException {
  255.        
  256.         int counter = 0;
  257.        
  258.         try (Scanner scanner = new Scanner(new FileInputStream(file)))
  259.         {
  260.             while (scanner.hasNext()) {
  261.                 if (check(scanner.next(),word))
  262.                     ++counter;
  263.             }
  264.            
  265.         }
  266.        
  267.         return counter;
  268.        
  269.     }
  270.    
  271.     static boolean check(String word1, String word2) {
  272.        
  273.         char bukva = word1.charAt(word1.length()-1);
  274.        
  275.         return word1.equals(word2) ||
  276.                 ( (!Character.isLetter(bukva) || !Character.isDigit(bukva))&&word1.substring(0, word1.length()-1).equals(word2));
  277.        
  278.     }
  279.    
  280. }
  281. /*Задача 5 Problem 5 (1 / 1)
  282. Некој систем за е-учење генерира извештаи за оценки на студенти по предмети во CSV (Comma Separated Values) формат. Да се напише Java програма, која на екран ќе го отпечати просекот на секој студент од датотеката rezultati.csv (види слика), како и просечната оценка што ја имаат студентите по секој од предметите наведени во првата редица. Програмата треба да работи за произволен број на редици.
  283.  
  284. Студент,КРС,НРС,АОК
  285. 11234,8,9,8
  286. 13456,6,7,9
  287. 11111,7,8,8
  288. 10123,10,10,10
  289.  
  290. Бонус: За подобра читливост на извештајот, прочитаната rezultati.csv датотека трансформирајте ја во TSV (Tab Separated Values) формат и снимете ја како rezultati.tsv.
  291.  
  292. Решение: Решението од HW01_5.java фајлот го поставувате тука со copy-paste*/
  293.  
  294.  
  295. import java.io.BufferedReader;
  296. import java.io.File;
  297. import java.io.FileNotFoundException;
  298. import java.io.FileReader;
  299. import java.io.IOException;
  300. import java.io.PrintStream;
  301. import java.util.ArrayList;
  302. import java.util.List;
  303.  
  304. public class HW01_5 {
  305.    
  306.     static String SOURCE = "rezultati.csv";
  307.     static String DESTINATION = "rezultati.tsv";
  308.    
  309.     public static void main(String[] args) throws IOException {
  310.        
  311.         File inputFile = new File(SOURCE);
  312.         File outputFile = new File(DESTINATION);
  313.        
  314.         if (!inputFile.exists())
  315.             throw new FileNotFoundException();
  316.        
  317.         List<Student> students = new ArrayList<>();
  318.         List<Subject> subjects = new ArrayList<>();
  319.        
  320.  
  321.         readInput(inputFile,students,subjects);
  322.  
  323.         writeOutput(outputFile,students,subjects);
  324.  
  325.        
  326.     }
  327.    
  328.     static void readInput(File file, List<Student> students, List<Subject> subjects) throws IOException {
  329.        
  330.         BufferedReader reader = null;
  331.         try {
  332.             reader = new BufferedReader(new FileReader(file));
  333.            
  334.             String line = reader.readLine();
  335.             String parts[] = line.split(",");
  336.             createSubjects(subjects,parts);
  337.            
  338.             while ((line = reader.readLine()) != null) {
  339.                 parts = line.split(",");
  340.                 students.add(new Student(parts));
  341.                 updateSubjects(subjects,parts);
  342.             }
  343.  
  344.         }
  345.         finally {
  346.             if (reader != null) reader.close();
  347.  
  348.         }
  349.        
  350.     }
  351.    
  352.     static void writeOutput(File file, List<Student> students, List<Subject> subjects) throws IOException {
  353.        
  354.         PrintStream writer = null;
  355.         try {
  356.             writer = new PrintStream(file);
  357.             writer.println("Prosechna ocenka po studenti:");
  358.             writer.println(String.format("%-10s\t%s","Index:","Ocenka:"));
  359.             for (Student student : students) {
  360.                 writer.println(String.format("%-10s\t%.2f", student.getIndex(),student.getAvgGrade()));
  361.             }
  362.             writer.println("Prosechna ocenka po predmeti:");
  363.             writer.println(String.format("%-10s\t%s","Predmet:","Ocenka:"));
  364.             for (Subject subject : subjects) {
  365.                 writer.println(String.format("%-10s\t%.2f", subject.getName(),subject.getAvgGrade()));
  366.             }
  367.  
  368.         }
  369.         finally {
  370.             if (writer != null) writer.close();
  371.         }
  372.        
  373.        
  374.     }
  375.    
  376.     static void createSubjects(List<Subject> subjects,String [] parts) {
  377.        
  378.         for (int i=1; i< parts.length; ++i)
  379.             subjects.add(new Subject(parts[i]));
  380.        
  381.     }
  382.    
  383.     static void updateSubjects(List<Subject> subjects, String[] parts) {
  384.        
  385.         for (int i=1; i < parts.length; ++i )
  386.             subjects.get(i-1).addGrade(parts[i]);
  387.     }
  388.    
  389.    
  390.  
  391. }
  392.  
  393. class Student  {
  394.    
  395.     private long index;
  396.     private int[] grades;
  397.    
  398.     public Student(String []parts) {
  399.         this.index = Long.parseLong(parts[0]);
  400.         grades = new int[parts.length-1];
  401.         for (int i=1; i < parts.length; ++i)
  402.             grades[i-1] = Integer.parseInt(parts[i]);
  403.     }
  404.    
  405.     public double getAvgGrade() {
  406.         double sum = 0;
  407.         for (Integer grade : grades)
  408.             sum += grade;
  409.         return sum / grades.length;
  410.     }
  411.    
  412.     public long getIndex() {
  413.         return index;
  414.     }
  415.    
  416. }
  417.  
  418. class Subject {
  419.    
  420.     private String name;
  421.     private List<Integer> grades;
  422.    
  423.     public Subject(String name) {
  424.         this.name = name;
  425.         this.grades = new ArrayList<>();
  426.     }
  427.    
  428.     public double getAvgGrade() {
  429.         return grades.stream()
  430.                 .mapToDouble(each -> Double.valueOf(each))
  431.                 .sum() / grades.size();
  432.     }
  433.    
  434.     public void addGrade(String grade) {
  435.         grades.add(Integer.parseInt(grade));
  436.     }
  437.    
  438.     public String getName() {
  439.         return name;
  440.     }
  441.    
  442.    
  443. }
Add Comment
Please, Sign In to add comment