读取文件并将字符串数组转化为整形数组

举例:通过读取文件,求一维数组的最大子数组

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

public class xieru {
    public static void main(String[] args)  throws IOException{
        //文件读入数组
        try {            
            String encoding = "UTF-8";            
            File file = new File("D:\\zhengshu.txt");//文档路径            
            if (file.isFile() && file.exists()) {                
                InputStreamReader read = new InputStreamReader(new FileInputStream(file), encoding);                
                BufferedReader bufferedReader = new BufferedReader(read);                
                String temp;
                int[] a = null;
                while ((temp = bufferedReader.readLine()) != null) {    
                     int[] ary = aryChange(temp);//通过函数把字符串数组解析成整数数组                
                     a = ary;              
                    System.out.println("读取:"+temp);//打印                            
                    }                
                read.close();
                System.out.println("最大子数组:"+max(a));//输出最大子数组
            } else {                
                    System.out.println("找不到指定的文件");            
                    }        
            }catch (Exception e) {            
                System.out.println("读取文件内容出错");            
                e.printStackTrace();        
            }
    }

    public static int[] aryChange(String temp) {
        /**
         * 字符串数组解析成整型数组
         */ 
        String[] ss = temp.trim().split("\\s+");// .trim()可以去掉首尾多余的空格
                                                // .split("\\s+")表示用正则表达式去匹配切割
                                                //   \\s+表示匹配一个或者以上的空白符
        int[] ary = new int[ss.length];
        for (int i = 0; i < ary.length; i++) {
            ary[i] = Integer.parseInt(ss[i]);// 解析数组的每一个元素
        }
        return ary;// 返回一个整型数组
    }        
    public static int max(int a[]) {
        /**
         * 求一维数组最大子数组
         */
        int x=a.length;
        int b[][]=new int[x][x];//存子数组
        int c[]=new int[x];//存二维数组每一行的最大值
        for(int i=0;i<x;i++) {//所有子数组存入二维数组中:以第i个开头的子数组们存入第i行
            for(int j=0;j<x;j++) {//求出二维数组的一行
                int sum=0;
                for(int s=i;s<=j;s++){//求每一个子数组                
                sum+=a[s];
                }
                b[i][j]=sum;//存子数组
            }
        };        
        for(int i=0;i<x;i++) {//i为行            
            for(int j=0;j<x;j++) {//j为列
                if(b[i][j]>c[i]) {                
                    c[i]=b[i][j];
                }
            }
        }
        int s=0;
        for(int i=0;i<c.length;i++) {    
            
            if(s<c[i]) {
                s=c[i];
            }
        };
        return s;
    }

}

运行结果:

猜你喜欢

转载自www.cnblogs.com/sengzhao666/p/10612687.html