个人作业2
設計思路 : 本題為個人作業1的續 ?要求在數量級 與數值范圍上做突破 同時要拋出錯誤 安全退出
? 首先 在數量級上 我使用了double 類型 ?在數量上 for循環是可以的 但是比較慢 ?我試了100萬100萬級 的數沒報錯 但是顯示的 比較慢 不知道是神魔原因
package main; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.PrintStream; import java.util.Scanner; public class Item { @SuppressWarnings("resource")public static void main(String args[]) throws Exception { System.out.println("輸入數量 n和數量級m:");Scanner in=new Scanner(System.in);int n=in.nextInt();Scanner in1=new Scanner(System.in);int m=in1.nextInt();PrintStream ps = new PrintStream("C:\\Users\\long.19981105\\Desktop/Ditie.txt");for(int i=0;i<n;i++) {System.setOut(ps);//把創建的打印輸出流賦給系統。即系統下次向 ps輸出System.out.print(random(m)+" ");}//在txt文件中輸出 n 個 數量級 為 m 的數。 File file = new File("C:\\Users\\long.19981105\\Desktop/Ditie.txt");double[] a = getLineFromTxt(file," ");for(int i = 0; i< a.length; i++){System.out.println("a["+i+"] = "+a[i]);}System.out.println(findMax(a));}/** 讀取txt到數組*/public static double[] getLineFromTxt(File file, String split) throws Exception{BufferedReader br = new BufferedReader(new FileReader(file));String firstLine = br.readLine(); //就讀第一行String[] arrs = firstLine.split(" ");//將字符數組轉為double數組double[] arr = new double[arrs.length];for(int i = 0; i< arr.length; i++){arr[i] = Double.parseDouble(arrs[i]);}if(br!= null){br.close();br = null;}return arr;}/** 最大子數組 和*/public static double findMax(double array[]){//加上約束條件,防止當數組為空時造成數組越界if (array.length == 0) {return 0;}double max = array[0];double sum = 0;for(int i=0; i<array.length; i++){ //如果加上某個元素sum>=0的話,就加;//當數組全為負數的時候只要有加法就一定比原來的數小,此時就相當于找出數組內最大的數 if(sum >= 0) { sum += array[i]; }else{ sum = array[i]; //否則從當前位置重新計算 }if(sum > max){ max = sum; }} return max; }/** 生成m數量級的隨機數*/public static int random(int m) {int num=(int)((Math.random())*m);return num;}/** 輸出到文件中*/public static void writeFile(){try {File writeName = new File("C:\\\\Users\\\\long.19981105\\\\Desktop/Ditie.txt"); // 相對路徑,如果沒有則要建立一個新的output.txt文件writeName.createNewFile(); // 創建新文件,有同名的文件的話直接覆蓋try (FileWriter writer = new FileWriter(writeName);BufferedWriter out = new BufferedWriter(writer)) {out.write(""); // \r\n即為換行out.write(""); // \r\n即為換行out.flush(); // 把緩存區內容壓入文件 }} catch (IOException e) {e.printStackTrace();}}}100萬數量級的 未能算出結果 ?拋出錯誤也未能實現
個人反思 :
? ?數量級 不能僅用數字類型來限定 ?現實生活中 總會有超出 范圍的一天?
代碼要有 現實意義 安全退出 是數據保存的重要依據
轉載于:https://www.cnblogs.com/1983185414xpl/p/10543915.html
總結
- 上一篇: 爬虫开发10.scrapy框架之日志等级
- 下一篇: HNOI2013 游走