标签:
package Question; import java.io.*; import java.text.DecimalFormat; public class Normalization { public static void main(String args[]) throws Exception{ // 定义一个输入流用来获取最大和最小值 FileReader file = null; BufferedReader buffer = null; file = new FileReader("D:\\num.txt"); buffer = new BufferedReader(file); // 定义文件的输入流 String str = null; FileReader fr = null; BufferedReader br = null; fr = new FileReader("D:\\from.txt"); // 定义文件的输出流 FileWriter fw = null; BufferedWriter bw = null; fw = new FileWriter("D:\\to.txt"); br = new BufferedReader(fr); bw = new BufferedWriter(fw); // 获得最大值和最小值 // 注意这里的值一定要和数据的数量相对应 double data[] = new double[8760]; int flag = 0; //br.mark((int)file.length() + 1); while((str = buffer.readLine()) != null){ double strNum = Double.parseDouble(str); data[flag] = strNum; flag++; } //br.reset(); buffer.close(); double maxNum = findMaxNum(data); double minNum = findMinNum(data); System.out.println("min = "+minNum); System.out.println("max = "+maxNum); int temp = 0; while((str = br.readLine()) != null){ // 将字符串转换成数值 double strNum = Double.parseDouble(str); // 将数组进行归一化操作,返回的就是字符串类型了 String afterNormal = NumToOne(strNum, maxNum, minNum); //System.out.println(afterNormal); temp++; // 将字符串写入另一个文件 bw.write(afterNormal); bw.newLine(); bw.flush(); } br.close(); System.out.println("共处理数据 "+temp+" 行"); } // 遍历数组找到最大值 public static double findMaxNum(double data[]){ double max = 0; for(int i = 0; i < data.length; i++){ if(data[i] > max){ max = data[i]; } } return max; } // 遍历数组找到最小值 public static double findMinNum(double data[]){ double min = data[0]; for(int i = 1; i < data.length; i++){ if(data[i] == 0){ System.out.println("为0的元素是:"+(i + 1)); } if(data[i] <= min){ min = data[i]; } } return min; } // 对某个数进行归一化处理 public static String NumToOne(double num, double max, double min){ double numChange = (num - min)/(max - min); DecimalFormat d = new DecimalFormat("0.00000"); return d.format(numChange); } }
标签:
原文地址:http://blog.csdn.net/jinhuoxingkong/article/details/51812254