1.要求数组从文件读取。
2.如果输入的数组很大,并且有很多大的数字,就会产生比较大的结果(考虑一下数的溢出),请保持你的程序正常输出。
3.另外,如果输入文件的参数有错误,这个程序应该能正确退出,并显示相应的错误。任何输入错误都不能导致你的程序崩溃。
代码:
1 package shuzu; 2 3 import java.io.BufferedReader; 4 import java.io.File; 5 import java.io.FileInputStream; 6 import java.io.FileOutputStream; 7 import java.io.FileReader; 8 import java.io.FileWriter; 9 import java.io.IOException; 10 import java.io.InputStreamReader; 11 import java.io.OutputStream; 12 import java.math.BigInteger; 13 import java.util.ArrayList; 14 import java.util.List; 15 import java.util.Scanner; 16 import java.util.*; 17 public class shuzu { 18 public static void main(String[] args) throws Exception{ 19 File f = new File("数组实验文件.txt"); 20 judeFileExists(f); 21 OutputStream out = new FileOutputStream(f,true); 22 Scanner in=new Scanner(System.in); 23 System.out.println("请输入产生随机数的数量:"); 24 String nums; 25 int n; 26 while(true) 27 { 28 try 29 { 30 nums=in.next() ; 31 n=Integer.parseInt(nums) ; 32 break ; 33 } 34 catch(Exception e) 35 { 36 System.out.println("只能输入整数") ; 37 } 38 } 39 for(int i=0;i<n;i++) 40 { 41 java.util.Random r=new java.util.Random(); 42 String s=Integer.toString(r.nextInt()); 43 out.write(s.getBytes()); 44 out.write('\r'); 45 out.write('\n'); 46 } 47 List list = new ArrayList(); 48 BufferedReader bw = new BufferedReader(new FileReader(f)); 49 String line = null; 50 while((line = bw.readLine()) != null){ 51 list.add(line); 52 } 53 //bw.close(); 54 int a=list.size(); 55 String[] li=new String[a]; 56 for(int i=0;i<list.size();i++) 57 { 58 li[i]=(String) list.get(i); 59 System.out.println(li[i]); 60 } 61 BigInteger maxsum = new BigInteger("0"); 62 BigInteger maxstart = new BigInteger("0"); 63 BigInteger x = new BigInteger("0"); 64 maxsum = new BigInteger(li[0]); 65 BigInteger y; 66 for(int i = 0;i < list.size();i++) 67 { 68 if (maxstart.compareTo(x)!=1) { 69 maxstart = new BigInteger(li[i]); 70 }else { 71 y= new BigInteger(li[i]); 72 BigInteger v=maxstart.add(y); 73 maxstart=v; 74 } 75 76 if (maxsum.compareTo(maxstart)<0) { 77 maxsum = maxstart; 78 } 79 } 80 System.out.println("最大值为:" + maxsum); 81 FileWriter fileWriter =new FileWriter(f); 82 fileWriter.flush(); 83 fileWriter.close(); 84 String line1 = null; 85 if((line1 = bw.readLine()) == null){ 86 System.out.println("文件清空成功");; 87 } 88 89 } 90 public static void judeFileExists(File file) { 91 if (file.exists()) { 92 System.out.println("file exists"); 93 } else { 94 System.out.println("file not exists, create it ..."); 95 try { 96 file.createNewFile(); 97 } catch (IOException e) { 98 // TODO Auto-generated catch block 99 e.printStackTrace(); 100 } 101 } 102 } 103 }