java 作业求助 io流输入txt计算最大最小平均值...共三题

1个回答

  • 先生成你需要的文件,然后再读入文件,并计算结果。

    import java.io.File;

    import java.util.*;

    import java.util.Random;

    import java.io.BufferedReader;

    import java.io.FileWriter;

    import java.io.FileReader;

    import java.io.IOException;

    import java.io.FileNotFoundException;

    public class Demo {

    x09public static void writefile() throws IOException {

    x09x09FileWriter fileWriter=new FileWriter("c:\fileIn.txt");

    x09x09Random ran1=new Random();

    x09x09for(int i = 0; i < 20;i++) {

    x09x09x09int ww = ran1.nextInt()%150;

    System.out.println(ww);

    x09x09x09fileWriter.write(String.valueOf(ww)+"n");

    }

    x09x09fileWriter.flush();

    x09x09fileWriter.close();

    x09}

    x09

    x09public static void readfile() throws IOException {

    x09x09//FileReader fileReader=new FileReader("c:\fileIn.txt");

    x09x09File file = new File("C:/fileIn.txt");

    x09x09BufferedReader reader = null;

    x09x09String tempString = null;

    x09x09//Arraylist new_input = new

    x09x09ArrayList new_input = new ArrayList();

    x09x09int line = 0;

    x09x09int less_than = 0;

    x09x09int middle_num = 0;

    x09x09int bigger_num =0;

    x09x09int sum =0;

    x09x09int max =0;

    x09x09int min = 0;

    x09x09try {

    x09x09x09reader = new BufferedReader(new FileReader(file));

    x09x09x09while ((tempString = reader.readLine()) != null) {

    x09x09x09x09System.out.println("Line"+ line + ":" +tempString);

    x09x09x09x09int aa = Integer.parseInt(tempString);

    x09x09x09x09new_input.add(aa);

    x09x09x09x09System.out.println("Line"+ line + ":" +aa);

    x09x09x09x09line ++ ;

    x09x09x09}

    x09x09x09reader.close();

    x09x09} catch (FileNotFoundException e) {

    x09x09x09// TODO Auto-generated catch block

    x09x09x09e.printStackTrace();

    x09x09}

    x09x09//next is to process the lines

    x09x09line = 0;

    x09x09for(int x:new_input) {

    x09x09x09sum +=x;

    x09x09x09if (line ==0) { max = x; min =x; }

    x09x09x09if (x > max) max =x;

    x09x09x09if (x < min) min =x;

    x09x09x09line++;

    x09x09}

    x09x09System.out.println("sum is : " +sum);

    x09x09System.out.println("max is : " +max);

    x09x09System.out.println("min is : " +min);

    x09x09System.out.println("num is : " +line);

    x09x09System.out.println("Average is : " +sum/line);

    x09x09//next is to write file

    x09x09FileWriter fileWriter=new FileWriter("c:\fileOut.txt");

    x09x09float aaaa = (float)sum/line;

    x09x09fileWriter.write("average is "+aaaa+ "n");

    x09x09fileWriter.write("max is "+max+ "n");

    x09x09fileWriter.write("min is "+min+ "n");

    x09x09fileWriter.flush();

    x09x09fileWriter.close();

    x09}x09

    public static void main(String[] args) throws Exception {

    x09x09Demo demo1 = new Demo();

    x09x09demo1.writefile();

    x09x09demo1.readfile();

    }

    }