分步进行数组的求和

骑猪看日落 2022-01-07 12:05 279阅读 0赞
  1. package shuzu;
  2. import java.io.BufferedReader;
  3. import java.io.FileNotFoundException;
  4. import java.io.FileReader;
  5. import java.io.FileWriter;
  6. import java.io.IOException;
  7. import java.util.ArrayList;
  8. import java.util.Scanner;
  9. public class Test {
  10. public static void main(String[] args) throws IOException {
  11. Scanner sc = new Scanner(System.in);
  12. try{
  13. FileWriter fw =new FileWriter("text.txt");
  14. for(int i=0;i<200;i++) {
  15. long x=(long)(Math.random()*200)*(Math.random()>0.5?1:-1);
  16. String y=""+x;
  17. fw.write(y);
  18. fw.write("\r\n");
  19. // System.out.println(y);
  20. }
  21. fw.close();}
  22. catch(FileNotFoundException e){
  23. e.printStackTrace();
  24. }
  25. ArrayList<String> arrList = new ArrayList<>();
  26. try {
  27. FileReader fr = new FileReader("text.txt");
  28. BufferedReader bf = new BufferedReader(fr);
  29. String st;
  30. while ((st = bf.readLine()) != null) {
  31. arrList.add(st);
  32. }
  33. bf.close();
  34. fr.close();
  35. } catch (FileNotFoundException e) {
  36. // TODO Auto-generated catch block
  37. e.printStackTrace();
  38. }
  39. long a[] = new long[arrList.size()];
  40. for (int i = 0; i <arrList.size(); i++) {
  41. String s=arrList.get(i);
  42. a[i] = (long) Double.parseDouble(s);
  43. }
  44. long max=a[0];
  45. long sum=a[0];
  46. System.out.println("1.执行 2.按步执行");
  47. int m=sc.nextInt();
  48. switch(m) {
  49. case 1:{
  50. for(int i=1;i<a.length;i++) {
  51. if(sum<0)
  52. sum=a[i];
  53. else
  54. sum+=a[i];
  55. if(sum>max) max=sum;
  56. System.out.print("子数组和最大值为"+max);
  57. System.out.println("到第"+(i+1)+"位");
  58. System.out.println();
  59. }
  60. System.out.println("最大子数组和:"+max);
  61. }break;
  62. case 2:
  63. {
  64. for(int i=1;i<=a.length;i++) {
  65. if(sum<0)
  66. sum=a[i];
  67. else
  68. sum+=a[i];
  69. if(sum>max) max=sum;
  70. System.out.print("当前子数组和最大值为"+max);
  71. System.out.println("当前检查到第"+i+"位");
  72. System.out.println();
  73. System.out.println("1.继续2.回上一步");
  74. int n = sc.nextInt();
  75. switch(n) {
  76. case 1:break;
  77. case 2:{
  78. long max1=a[0];
  79. long sum1=a[0];
  80. System.out.println("输入位数");
  81. int j=sc.nextInt();
  82. for(int k=1;k<=j;k++) {
  83. if(sum1<0)
  84. sum1=a[k];
  85. else
  86. sum1+=a[k];
  87. if(sum1>max1) max1=sum1;
  88. }
  89. System.out.print("子数组和最大值为"+max1);
  90. System.out.println("当前检查到第"+j+"位");
  91. }break;
  92. }
  93. }System.out.println("最大子数组和:"+max);
  94. }
  95. }
  96. }
  97. }

  思路为在文档获取数组后,按之前的方法进行子数组的和运算,按老师的要求是要加一个步骤的分布展示,将子数组的加和加入一个i,用来定位此时运算在哪里,这样就能一步一步的显示运算步骤。

问题:这个一步一步的展示真的想不明白,在网上寻求思路代码才加和上去。

自己要把数组求和这一类问题好好的总结一下,争取弄明白其中的思路问题,尤其是那个步骤的分部。

转载于:https://www.cnblogs.com/jhl1234/p/11043811.html

发表评论

表情:
评论列表 (有 0 条评论,279人围观)

还没有评论,来说两句吧...

相关阅读