一、设计思路
1、文件读取操作(上学期做过,FileWriter) 新学知识BufferWriter。
2、数据过大溢出问题,新学知识:运用Biginteger进行处理。
3、课程前面的进行数组的最大值取值问题。
二、题目
三、源代码
package test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.math.BigInteger; import java.util.Scanner; public class shu1 { static String s = ""; static Scanner in = new Scanner(System.in); public static void main(String[] args) throws IOException { chansheng(); read(); //System.out.println(s); String[] rang = s.split("[^(-9--10-9)]"); //按照数字的方式对读入的字符串进行划分,并存入到rang数组中 // int value = 0; // int sum =0; BigInteger value = new BigInteger("0"); BigInteger sum = new BigInteger(String.valueOf(rang[0])); //将数组中的第一个值赋值给sum //sum = Integer.parseInt(rang[0]); for(int i = 0;i < rang.length;i++) { int a = value.compareTo(BigInteger.valueOf(0)); if ( a == 0 || a == -1) { //value = Integer.parseInt(rang[i]); //当用于记录的值小于等于0时就无需对其进行相加了,此时就等于下一个值 value = new BigInteger(String.valueOf(rang[i])); }else { value.add(new BigInteger(String.valueOf(rang[i]))); //value += Integer.parseInt(rang[i]); //当value的值仍大于0时就继续相加 } if (sum.compareTo(value) == -1) { //用sum等于子数组的最大值,若value的值大于sum的值,则将value赋值给sum sum = value; } } System.out.println("最大值为:" + sum); } //读取文件的方法 public static String read() throws IOException { FileInputStream fis = new FileInputStream("D:\代码文件\文本文件\数组.txt"); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String temp = ""; while((temp = br.readLine()) != null) s = s + temp + " "; //将文件中的文章都存入字符串s中 fis.close();//关闭文件 br.close(); return s; } //产生随机数,并将其写入到文件的操作 public static void chansheng() throws IOException { int n; System.out.println("请输入计算的数据量"); n = in.nextInt(); File file1 = new File("D:\代码文件\文本文件\数组.txt"); FileWriter out = null; try { out = new FileWriter(file1); } catch (IOException e) { e.printStackTrace(); } BufferedWriter bw = new BufferedWriter(out); for(int i = 0;i < n ; i++) { int ran = (int)(Math.random()*10000000) - (int)(Math.random()*100000000); BigInteger a = new BigInteger(String.valueOf(ran)); //bw.write(String.valueOf(ran) + " "); bw.write(String.valueOf(a) + " "); } bw.close(); } }