客户作业---读取文件实现求数组中所有子数组和的最大值


题目内容:

思路:这道题难道就在于处理异常,那么就要用到异常机制。读文件我是一行一行读的,方便计算。在大数方面,我用了BigInteger,可以计算无穷,看代码

package daliyTest1;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.math.BigInteger;

public class GetBiggestArrayByFile {
    public static void main(String[] args) {
        BigInteger a[] = new BigInteger[100000];
        int i = 1;
        File file = new File("C:\\Users\\MACHENIKE\\Desktop\\新建文本文档.txt");
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            String value="";
            try {
                while((value=reader.readLine())!=null) {
                    try {   
                        a[i++] = new BigInteger(value);
                    } catch (Exception e) {
                        System.out.println("文件里存在非数字的符号!!");;
                    }
                }
            
                for(int j=2;j<i;j++) {
                    if((a[j].compareTo(a[j].add(a[j-1]))<0)){
                        a[j] = a[j].add(a[j-1]);
                    }
                }
                BigInteger ans_1 = BigInteger.valueOf(-10000);
                // 对数组取最大值
                for(int j=1;j<i;j++) {
                    ans_1 = ans_1.compareTo(a[j])<=0?a[j]:ans_1;
                }
                System.out.println("最大子数组和为:"+ans_1);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            System.out.println("不存在该文件");
        }
    }
}

输出结果:

文件内容:

大数测试输出结果:

文件内容:

如果有不了解BigInteger的,可以百度查查学习,比较实用,而且简单

猜你喜欢

转载自www.cnblogs.com/yangxiao-/p/12368364.html