关于最大子序和的算法问题(二)

  这次我们老师让我们在上次的基础上做出完善,要求我们能使我们的数组能够从文件中读取,并且要求我们要能够支持特别大的数,让我们的程序不会崩溃。

  我也是个基础并不好的学生,所以说还是从刚一开始就要翻阅其他人的代码,充实自己的代码库。

  直接上代码:

  

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);
    }

 

posted @ 2019-03-17 21:36  *尹天仇  阅读(154)  评论(0编辑  收藏  举报