Loading


随笔 - 146  文章 - 2  评论 - 2  阅读 - 30396 

作业1链接:https://www.cnblogs.com/wxy2000/p/10506716.html

要求:

  • 数组从文件读取
  • 输入很大的数组,和很多大的数字保持你的程序正常输出
  • 若输入文件的参数有错误,程序能正常退出,并显示相应的错误。任何错误都不能使程序崩溃

设计思路:

  1. 利用random随机生成很大的数组
  2. 用out.write将数组写入到txt文件中
  3. 采用biginteger解决int型数据的大小受到限制的问题
  4. 求最大子数组和的方法同作业1

 

遇到的问题:

  1. 不了解biginteger的使用,后来经过同学的知道解决了
  2. 输入某些异常时没用提示,正在完善

源代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
 
 
public class Q_31 {
    static Scanner sc=new Scanner(System.in);
     static float d=Float.NEGATIVE_INFINITY;
 
 public static void main(String[] args) throws IOException {
  
      
      
    //输入数组长度
    int n1=0;
    System.out.println("请输入数组的长度");
    n1=sc.nextInt();
     
 
    //随机生成数组
  int[] a=new int [n1];
  
    //System.out.println("请输入"+n1+"个 整数");
  for(int i=0;i<n1;i++){
       
        a[i] =(int) (Math.random()*1000)-500;
        System.out.println(a[i]);
        
        
      }
     
     
     
    //调用函数输出结果
  int maxSum = getMaxSum(a);
  System.out.println("最大子数组的和为:" + maxSum);
 
 
   
   
   
  
  File file = new File("d:\\array.txt");  //存放数组数据的文件
  
  FileWriter out = new FileWriter(file);  //文件写入流
  
  //将数组中的数据写入到文件中
  for(int i=0;i<a.length;i++){
    
    out.write(a[i]+"\t");
   
   //out.write("\r\n");
  }
 
  out.write("最大子数组的和为:" + maxSum);
  out.close();
  
  
  }
 
 private static int getMaxSum(int[] a) {
        
        int n = a.length;
       int max1 =(int) d;//令最大值等于无穷小
        for (int i = 0; i < n; i++) {
            int sum = 0;
            for (int j = i; j < n; j++) {
                sum += a[j];
                if (max1 < sum) {
                    max1 = sum;
                }
            }
        }
 
        return max1;
    }
 }

  

 

 

运行结果:

 

 

 

作者:wxy2000

出处:https://www.cnblogs.com/wxy2000/p/10590336.html

版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。

posted on   一氓  阅读(133)  评论(0编辑  收藏  举报
more_horiz
keyboard_arrow_up light_mode palette
选择主题
点击右上角即可分享
微信分享提示