求数组的子数组之和的最大值II
阅读原文时间:2023年07月10日阅读:1

这次在求数组的子数组之和的最大值的条件下又增加了新的约束:

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

设计思路:

  1.首先就是对文件的读取,从文件中读取数组,将按行读取的数组进行分割,存储

  2.接入求最大值函数,调用数组,调整类型,对于大数进行处理,在求数组的子数组之和的最大值处参考了O(n)的算法

  3.对文件读取等进行异常处理

截图:

1 package test2;
2 import java.io.BufferedReader;
3 import java.io.File;
4 import java.io.FileReader;
5 import java.io.IOException;
6 import java.util.ArrayList;
7
8 public class shuzu2 {
9
10 public static void readFileByLines(String fileName) {
11 File file = new File(fileName);
12 BufferedReader reader = null;
13 try {
14 reader = new BufferedReader(new FileReader(file));
15 String tempString = null;
16
17 while ((tempString = reader.readLine()) != null) {
18
19 System.out.println(tempString);
20
21 }
22 reader.close();
23 } catch (IOException e) {
24 e.printStackTrace();
25 } finally {
26 if (reader != null) {
27 try {
28 reader.close();
29 } catch (IOException e1) {
30 }
31 }
32 }
33 }
34
35 public static long[] toArrayByFileReader1(String name) {
36 // 使用ArrayList来存储每行读取到的字符串
37 ArrayList arrayList = new ArrayList<>();
38 try {
39 FileReader fr = new FileReader(name);
40 BufferedReader bf = new BufferedReader(fr);
41 String str;
42 // 按行读取字符串
43 while ((str = bf.readLine()) != null) {
44 arrayList.add(str);
45 }
46 bf.close();
47 fr.close();
48 } catch (IOException e) {
49 e.printStackTrace();
50 }
51 // 对ArrayList中存储的字符串进行处理
52 int length = arrayList.size();
53 long[] array = new long[length];
54 for (int i = 0; i < length; i++) { 55 String s = arrayList.get(i); 56 array[i] = Long.parseLong(s); 57 } 58 59 long f=0;//定义整形变量f,为子数组最大值 60 long sum=0;//定义整形变量sum,为子数组求和 61 for(int i=0;i f)
69 {
70 f = sum;
71 }
72 }
73
74 if(sum == 0)
75 {
76 for(int i=0;i<length;i++)
77 {
78 if(i == 0)
79 {
80 f = array[i];
81 }
82 if(f < array[i])
83 {
84 f = array[i];
85 }
86 }
87 }
88
89 System.out.println("该数组的子数组之和的最大值为:"+f);
90
91
92 // 返回数组
93 return array;
94 }
95
96
97 public static void main(String[] args) throws IOException{
98
99 String name = new String("E:\\Program Files\\eclipse操作\\shuzu\\src\\test2\\input.txt");
100
101 readFileByLines(name);
102 toArrayByFileReader1(name);//文件路径
103
104 }
105 }

反思:

对于大数的处理还不是很熟悉,在课上听同学们的交流,应该采用随机生成数的方式,随机产生随机个数的数字,用来测试读取数字的最大个数,这一点没有实现,还有异常处理也没有实现,对于不合法数字、文件读取等方面的处理还不会。这次更充分的体现了分步的重要性,如果不分步的话,会感觉到十分吃力,会感觉到无从下手,这种东西还是得多练。