课堂练习2补充——求数组中最子数组的和
看下题目:

这道题,由于一些相关基本语法知识的忘记,使得延迟发表了这篇博客,参考同学的答案并复习了相关对象的方法知识后,发表了如下解题过程:
import java.io.*; import java.util.Scanner; public class SumArray3 { /* *前情回顾:上个程序我们实现了求数组的所有子数组的最大和为时间复杂度为o(n)的算法。 * 要求增加:要将使用的数组放在一个叫input.txt的文件中,文件格式是: * 数组的行数, * 数组的列数, * 每一行的元素,(用逗号分开) * 每一个数字都是有符号的32位整数。当然行和列都是整数。 */ public static int max(int a,int b) { return a>b?a:b; } public static void main(String[] args) throws IOException { Scanner scanner = new Scanner(new FileReader("D:\\IDEA\\demo1\\2022_0311\\src\\input.txt")); int row = 0,colum = 0,temprow = 0,tempcolum =0,sum1 = 0,sum2 = 0; //读取文件中的行数和列数 for(int i = 0; i < 2 && scanner.hasNextLine(); i++){ String line = scanner.nextLine(); if(i == 0){ row = Integer.parseInt(line.substring(0,line.indexOf(','))); }else{ colum = Integer.parseInt(line.substring(0,line.indexOf(','))); } } if(row <= 0 || colum <= 0){ System.out.println("行数列数错误"); return; } int [] shuzu = new int[row*colum]; int index = 0; //获取文件中的数组 for(temprow = 0; temprow < row && scanner.hasNextLine(); temprow++) { String line = scanner.nextLine(); for(tempcolum = 0; tempcolum < colum - 1 && !line.equals(""); tempcolum++){ shuzu[index++] = Integer.parseInt(line.substring(0,line.indexOf(','))); line = line.substring(line.indexOf(',') + 1, line.length()); } if(!line.equals("")){ shuzu[index++] = Integer.parseInt(line.substring(0)); tempcolum++; } if(tempcolum != colum){ System.out.println("列数错误"); return; } } if(temprow != row || scanner.hasNextLine()){ System.out.println("行数错误"); return; } int a[] = new int[100]; for(int i = 0; i < a.length && i < shuzu.length; i++){ a[i] = shuzu[i]; } sum1 = a[0]; for(int i = 0;i<5;i++) { sum2 = sum1; if(a[i+1]<0){ i++; sum1+=a[i]; sum1 = max(sum1,a[i+1]); }else{ sum1+=a[i+1]; } sum1=max(sum2,sum1); } System.out.println("最大子数组的和为:"+sum1); } }
目录结构:

文件内容:

输出结果:


浙公网安备 33010602011771号