代码之家  ›  专栏  ›  技术社区  ›  blockByblock

Java Move nextLine with方法

  •  -1
  • blockByblock  · 技术社区  · 6 年前

    我有一个多行文本文件,我需要将每一行分配给不同的数组。 我已经为此创建了一个方法,但它不起作用。这就是我的主要方法。

        public static void main(String[] args){
        String[] arr = new String[20];
        fromTextToArray(arr); //after this method call, the console needs to move next Line
        String[] arr2 = new String[20];
        fromTextToArray(arr2);
      }
    

    这就是我的方法。

     public static void fromTextToArray(String[] strArray) throws IOException{
        BufferedReader brTest = new BufferedReader(new FileReader("csalg.txt"));
        String text = brTest.readLine();
        brTest.readLine();
        strArray = text.split(",");
        System.out.println(Arrays.toString(strArray));
        text = brTest.readLine(); // this is where I try to move next line for my second array
    }
    

    文件中的数字:

    1    5 4 4 7 5 5 5 5 3 3 7 7 4 5 2
    2    4 5 4 3 4 5 2 3 4 5 5
    4    9 10 13 9 8 12 20 16 12 16 6 9 5 5 19 15 16 16 10
    8    3 5 1 3 2 7 2 4 7 6 1
    

    所需输出:

    arr[]={1,5,4,7,5,5,5,3,7,4,5,2}
    arr2[]={2,4,5,4,3,4,5,2,3,4,5,5}

    是否可以移动到方法中的下一行?或者有什么不同的方法?

    1 回复  |  直到 6 年前
        1
  •  1
  •   LenosV    6 年前

    您正在方法中声明读取器,因此每次都将从文件的开头开始。 此外,请使用“尝试使用”资源来处理关闭读卡器的问题,或者最终编写一个“尝试捕获”并自己关闭它。

    您可以让该方法决定字符串数组的长度,而无需这样做。

     public static void main(String[] args) throws IOException {
    
        try (BufferedReader brTest = new BufferedReader(new FileReader("s.txt"))) {
            String[] arr = fromTextToArray(brTest.readLine());// line 1
            brTest.readLine(); // skip line 2
            String[] arr2 = fromTextToArray(brTest.readLine());// line 3
            System.out.println(Arrays.toString(arr));
            System.out.println(Arrays.toString(arr2));
        }
    }
    
    public static String[] fromTextToArray(String text) throws IOException {
    
        String[] arr = text.split(",");
        return arr;
    }