第一次课堂练习-第二部分
1.思路:
通过Scanner、相对路径来读取文件,scanner.hasNextLine()函数读取下边对应行的内容。
2.源代码:
/** * @author migua * @version 1.0 * @date 2022/3/11 19:25 */ import java.io.*; import java.math.BigDecimal; import java.util.List; import java.util.Scanner; public class bb { public static void main(String[] args) { try { Scanner scanner = new Scanner(new FileReader("src/test.txt")); int row = 0; int column = 0; int tempRow, tempColumn; for (int i = 0; i < 2 && scanner.hasNextLine(); i++) { String L = scanner.nextLine(); if (i == 0) { row = Integer.parseInt(L.substring(0, L.indexOf(','))); } else { column = Integer.parseInt(L.substring(0, L.indexOf(','))); } } if (row <= 0 || column <= 0) { System.out.println("行数或者列数出错"); return; } int tempInt[] = new int[row * column]; int tempIndex = 0; for(tempRow =0;tempRow<row &&scanner.hasNextLine();tempRow++) { //不存在下一行或者已经读完该读的行 String L = scanner.nextLine(); for (tempColumn = 0; tempColumn < column - 1 && !L.equals(""); tempColumn++) { tempInt[tempIndex++] = Integer.parseInt(L.substring(0, L.indexOf(','))); //先获取从头开始至第一个逗号之间的数 L = L.substring(L.indexOf(',') + 1, L.length()); //将第一个逗号之后的值覆盖原来的值 } if (!L.equals("")) { tempInt[tempIndex++] = Integer.parseInt(L.substring(0)); tempColumn++; } if (tempColumn != column) { System.out.println("数据的列数不对"); return; } } if (tempRow != row || scanner.hasNextLine()) { System.out.println("数据的行数不对"); return; } BigDecimal max = new BigDecimal("0"); BigDecimal tempMax = new BigDecimal("0"); for (int i = 0; i < row * column; i++) { if (i == 0) { BigDecimal temp = new BigDecimal(tempInt[i]); tempMax=tempMax.add(temp); max=max.add(temp); //max = tempInt[i]; } else { if (tempMax.compareTo(new BigDecimal("0")) == -1) //tempMax < 0 { tempMax = new BigDecimal(tempInt[i]); } else { tempMax=tempMax.add(new BigDecimal(tempInt[i])); } } if (tempMax.compareTo(max) == 1) //tempMax > max { max = tempMax; } } System.out.println(max); } catch(FileNotFoundException e){ e.printStackTrace(); } } }
3.运行截图: