返回一个整数数组中最大子数组的和---第一次完善

本次的任务是

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

由于自己的水平还不高,只实现了将数组从文件读取,找到数组和最大的。

下面运用ArrayList定义数组实现文件读取功能代码如下:

public static int[] toArrayByFileReader1(String name) {
        // 使用ArrayList来存储每行读取到的字符串
        File file = new File(name);
        judeFileExists(file);
        ArrayList<String> arrayList = new ArrayList<>();
        try {
            FileReader fr = new FileReader(name);
            BufferedReader bf = new BufferedReader(fr);
            String str;
            // 按行读取字符串
            while ((str = bf.readLine()) != null) {
                arrayList.add(str);
            }
            bf.close();
            fr.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 对ArrayList中存储的字符串进行处理
        int length = arrayList.size();
        int[] array = new int[length];
        for (int i = 0; i < length; i++) {
            String s = arrayList.get(i);
            array[i] = Integer.parseInt(s);
             
        }
        // 返回数组
        return array;
    }
    public static void judeFileExists(File file) {
         if (file.exists()) {
             System.out.println("文件存在!");
                }
         else {
                      System.out.println("文件不存在!");
                      System.exit(0);
//                      try {
//                          file.createNewFile();
//                      } catch (IOException e) {
//                          // TODO Auto-generated catch block
//                          e.printStackTrace();
//                      }
                  }
          
              }

最后在写求最大数组和

public static void main(String[] args) throws IOException{
        // TODO Auto-generated method stub
        int[] a = toArrayByFileReader1("shuzu.txt");
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
        int sum=0,m=0;
        int max = 0;
        int [] b=new int[30];
        for(int j=0;j<a.length;j++)
        {
              sum=sum+a[j];
              b[m]=sum;
              m++;            
        }
        for(int k=0;k<m;k++)
        {
            System.out.println("sum="+b[k]); 
        
        }
        max=b[0];
        for(int i=1;i<m;i++)
        {
            if(max<b[i])
            {
                max=b[i];
            }
        }
        System.out.println("max="+max);
    }
    
原文地址:https://www.cnblogs.com/lishengming00/p/10548859.html