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

本次任务要求从文件读取数组,处理大数组和大数可能导致的溢出问题,输入参数错误时程序能正常退出并显示错误信息。博主因水平有限,仅实现从文件读取数组并找到数组和最大的功能,还给出运用ArrayList定义数组实现文件读取的代码。

本次的任务是

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

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

下面运用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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值