连续子数组和的最大值plus

package wodeshiyao;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Random;

public class asd{
    /**
     * 产生随机数储存到文本文件
     */
    public static void Writer() {
        // 获得路径
        String filepath = System.getProperty("user.dir"); // 获得当前工程路径
        filepath += "\\file.txt";
        File file = new File(filepath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            Random random = new Random();    //默认当前系统时间的毫秒数作为种子数
            for (int i = 0; i < 100; i++) {// 随机产生100个随机数
                int nums = 99999 - Math.round(random.nextFloat() * 100.0f);// 生成大小在100以内的正负整数
                bw.write(Integer.toString(nums));
                bw.newLine();
            }
            bw.write("1");
            bw.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 从文本文件中读取
     * 
     * @param filePath
     * @return
     */
    public static String[] readToString(String filePath) {
        File file = new File(filePath);
        Long filelength = file.length(); // 获取文件长度
        byte[] filecontent = new byte[filelength.intValue()];// 将文件长度强制转换为整形储存到byte数组
        try {
            FileInputStream in = new FileInputStream(file);
            in.read(filecontent);
            in.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String[] fileContentArr = new String(filecontent).split("\r\n");
        return fileContentArr;// 返回文件内容,默认编码
    }

    /**
     * 主函数
     * 
     * @param args
     */
    public static void main(String args[]) {
        Writer();
        String[] Arr = readToString("file.txt");
        int max = Integer.MIN_VALUE;// 设置成最小整数
        int sum = 0;// 记录数组个元素相加的和
        int[] x = new int[Arr.length];
        for (int i = 0; i < Arr.length; i++) {// 将个元素依次相加并进行判断
            x[i] = Integer.parseInt(Arr[i]);
            sum += x[i];
            if (sum > max) {// 如果求得总和大于之前的最大值的话,就将sum赋值给max
                max = sum;
            }
        }
        System.out.println("最大连续子数组的和为:" + max);
    }
}

猜你喜欢

转载自www.cnblogs.com/jmdd/p/10549605.html