Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.hungdh;
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.File;
- import java.io.FileNotFoundException;
- import java.io.FileReader;
- import java.io.FileWriter;
- import java.io.IOException;
- import java.util.Random;
- public class CodeForLove {
- /**
- *
- * @param path
- * @return mảng 10 phẩn tử, mỗi phần tử chứ số lần xuất hiện
- *
- * VD: điểm 1: 5 lần, điểm 2: 10 lần, ... điểm 10: 9 lần,
- * arrResult: {5, 10, ..., 9};
- */
- public static int[] readFile(String path) throws IOException {
- FileReader fr = new FileReader(new File(path));
- BufferedReader br = new BufferedReader(fr);
- int[] arrResult = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
- String num = "";
- while ((num = br.readLine()) != null) { // Đọc từng dòng, cho đến khi nào hết file
- try {
- int point = Integer.parseInt(num); // Ép "chữ số" đọc được về số
- arrResult[point - 1] += 1; // Tăng số lần xuất hiện tương ứng với điểm khảo sát
- } catch (NumberFormatException nfe) {
- nfe.printStackTrace();
- }
- }
- return arrResult;
- }
- /**
- * Method: ghi chuỗi s xuống file có đường dẫn path
- * @param path
- * @param s
- *
- */
- public static void writeFile(String path, String s) throws IOException {
- FileWriter fw = new FileWriter(new File(path));
- BufferedWriter bw = new BufferedWriter(fw);
- bw.write(s);
- bw.close();
- fw.close();
- }
- /**
- * Tạo mảng 100 phần tử, mỗi phần tử được sinh ngẫu nhiên từ 1- 10
- * random.nextInt(10): sẽ trả về giá trị ngẫu nhiên từ 0 - 9;
- */
- public static int[] Survey() {
- Random random = new Random();
- int[] arrSurvey = new int[100];
- for (int i = 0; i < 100; i++) {
- arrSurvey[i] = random.nextInt(10) + 1;
- }
- return arrSurvey;
- }
- /**
- * Method tính tỉ lệ khảo sát
- * @param path: đường dẫn file thứ 2
- * @param data: dữ liệu đã khảo sát
- */
- public static void calculateSurvey(String path, int[] data)
- throws IOException {
- StringBuffer s = new StringBuffer();
- for (int i = 0; i < data.length; i++) {
- s.append((i + 1) + "\t" + (float) data[i] / 100 + " %\n");
- }
- writeFile(path, s.toString());
- }
- public static void main(String[] args) {
- String file_1 = "Survey.txt";
- String file_2 = "Result.txt";
- int[] arrSurvey = Survey();
- System.out.println("Survey success");
- try {
- StringBuffer s = new StringBuffer();
- for (int i = 0; i < arrSurvey.length; i++) {
- s.append(arrSurvey[i] + "\n");
- }
- writeFile(file_1, s.toString());
- System.out
- .println("Survey data has been written to the file Survey.txt ");
- int[] arrResult = readFile(file_1);
- calculateSurvey(file_2, arrResult);
- System.out
- .println("Results of the survey has been written to the file Result.txt ");
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement