【问题标题】:Java-Move nextLine with methodJava-使用方法移动 nextLine
【发布时间】:2018-03-29 04:47:36
【问题描述】:

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

    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,3,7,4,5,2}
arr2[] = {2,4,5,4,3,4,5,2,3,4,5,5}

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

【问题讨论】:

    标签: java file io bufferedreader


    【解决方案1】:

    你在方法中声明了 reader,所以每次它都会从文件的开头开始。 另外,使用 try-with-resource 处理关闭 reader 或编写 try-catch-finaly 并自行关闭。

    你可以让方法决定字符串数组的长度,不需要你做。

     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;
    }
    

    【讨论】:

    • 感谢您的评论,但这只是获取该行并设置为它的数组。例如,arr2[0] 打印整行而不是第一个值。
    • 它用逗号字符分割值,你能添加一个输入和期望输出的例子吗?之后我也许可以提供帮助。
    • 我刚刚修复了它,它帮助很大!谢谢!
    猜你喜欢
    • 2017-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-29
    相关资源
    最近更新 更多