第三周总结
完成代码--返回一个整数数组中最大子数组的和(二)
这次,在上次的情况下增加了一些新的要求。
· 要求数组从文件读取。
· 如果输入的数组很大, 并且有很多大的数字, 就会产生比较大的结果 (考虑一下数的溢出), 请保证你的程序能正常输出。
好,下面就是对代码的构造。
首先,写一个写入文件的方法,并在这个方法中产生随机数(因为想看一下在这个程序是在多少数据量级下能够正确输出,一个一个按太麻烦了)
public static void Writer() {
// 获得路径
String filepath = System.getProperty("user.dir"); // 获取当前类的完整路径
filepath += "\\file.txt";
File file = new File(filepath);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
Random random = new Random();
for (int i = 0; i < 1000000; i++) {// 随机产生100000个随机数
int nums = 99999 - Math.round(random.nextFloat() * 1000000.0f);// 生成大小在1000000以内的正负整数
bw.write(Integer.toString(nums));
bw.newLine();
}
bw.write("1");
bw.close();
} catch (IOException e) {
e.printStackTrace();
}
}然后就是再从文件中读出这些数据,因为在读取的过程中,当遇到最后一个正数后面的数负数的话,就不会将后面的负数读取到,所以在写入文本的过程中,在最后加了一个“1”。
下面是读入文件的代码
public static String[] readToString(String filePath) {
File file = new File(filePath);
Long filelength = file.length(); // 获取文件长度
byte[] filecontent = new byte[filelength.intValue()];// 将文件长度强制转换为整形储存到byte数组
try {
FileInputStream in = new FileInputStream(file);
in.read(filecontent);
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String[] fileContentArr = new String(filecontent).split("\r\n");
return fileContentArr;// 返回文件内容,默认编码
}
这里使用byte数组来进行存储,并且用String数组进行分割。但是使用这个方法不能很好的解决数据溢出的问题。此问题待以后优化。
然后就是主函数。
public static void main(String args[]) {
Writer();
String[] Arr = readToString("file.txt");
int max = Integer.MIN_VALUE;// 设置成最小整数
int sum = 0;// 记录数组个元素相加的和
int[] x = new int[Arr.length];
for (int i = 0; i < Arr.length; i++) {// 将个元素依次相加并进行判断
x[i] = Integer.parseInt(Arr[i]);
sum += x[i];
if (sum > max) {// 如果求得总和大于之前的最大值的话,就将sum赋值给max
max = sum;
}
}
System.out.println("最大子数组的和为:" + max);
}
在从文件中读入的数据都是String型的,所以这里需要将读入的数据进行类型转化。
x[i] = Integer.parseInt(Arr[i]);
然后接可以输出正确的数据了,当然,数据是比较多的,所以,只能估算一下咯。
实验截图:
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 25岁的心里话
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现