• 返回一个整数数组中最大子数组的和(2)


    题目要求:

    • 要求数组从文件读取。
    • 如果输入的数组很大, 并且有很多大的数字, 就会产生比较大的结果 (考虑一下数的溢出), 请保证你的程序能正常输出。
    • 另外, 如果输入文件的参数有错误, 这个程序应该能正常退出, 并显示相应的错误信息。 任何输入错误都不能导致你的程序崩溃。

    思路和代码:

    可以看到,提出了新的要求,其中很明显的是数字溢出问题,和异常捕捉。对于数字溢出,我们可以使用BigInteger类,而异常捕捉直接try catch代码块即可。下面是代码和测试:
    public static void main(String[] args) throws IOException {
    	BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("F:\WorkSpace\Test\src\Teste\1.txt")));
    	List<BigInteger> a = new  ArrayList<>();
    	String file;
    	BigInteger max_ending_here,max_so_for;
    	max_ending_here = max_so_for = BigInteger.valueOf(Integer.MIN_VALUE);
    	while((file=bufferedReader.readLine())!=null) {
    		try {
    			BigInteger x = BigInteger.valueOf(Long.parseLong(file));
    			System.out.println(x);
    			a.add(x);
    		} catch (Exception e) {
    			System.err.println("存在非法字符 程序将退出!");
    			return;
    		}
    	}
    	bufferedReader.close();
    	for(BigInteger x:a) {
    		max_ending_here = x.max(max_ending_here.add(x));
    		max_so_for =max_so_for.max(max_ending_here);
    	}
    	System.out.println("-----------");
    	System.out.println(max_so_for);
    	
    }
    
    测试截图:有非法字符a:

    测试截图:无非法字符:

    总结:在遇到超过整数的上线的时候,可以使用java的BigInteger类进行转换和使用。关于算法其实还是上一篇的算法。

  • 相关阅读:
    final关键字
    多态
    java特性-封装
    super的使用
    ==和equals的区别
    面向对象的三大特征
    this和static的用法
    如何一步步使用国内yum源一键安装openstack-ocata版本基于centos7
    Zabbix 4.2 安装
    自动化运维神器-ansible
  • 原文地址:https://www.cnblogs.com/wushenjiang/p/12369857.html
Copyright © 2020-2023  润新知