简体   繁体   English

如何在java中访问字符串数组的动态数组的元素?

[英]How to access elements of a dynamic array of string arrays in java?

I'm trying to use opencsv ( http://opencsv.sourceforge.net/ ).我正在尝试使用 opencsv ( http://opencsv.sourceforge.net/ )。 There are examples included with the download of opencsv. opencsv 的下载中包含了一些示例。 Here's an excerpt of their example for creating a dynamic array:这是他们创建动态数组的示例的摘录:

CSVReader reader = new CSVReader(new FileReader(ADDRESS_FILE));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    System.out.println("Name: [" + nextLine[0] + "]\nAddress: [" + nextLine[1] + "]\nEmail: [" + nextLine[2] + "]");
}

The CSV file it reads is as follows:它读取的CSV文件如下:

Joe Demo,"2 Demo Street, Demoville, Australia. 2615",joe@someaddress.com
Jim Sample,"3 Sample Street, Sampleville, Australia. 2615",jim@sample.com
Jack Example,"1 Example Street, Exampleville, Australia. 2615",jack@example.com

If I move the println statement outside of the while loop, I get an error in Eclipse: "Null pointer access: the variable nextLine can only be null at this location."如果我将 println 语句移到 while 循环之外,我会在 Eclipse 中得到一个错误:“空指针访问:变量 nextLine 在这个位置只能为空。”

My guess is that nextLine has a pointer currently pointing to it's last position or past its last position.我的猜测是 nextLine 有一个当前指向它的最后一个位置或过去它的最后位置的指针。 I think my question is, how do I control that pointer?我想我的问题是,我如何控制那个指针?

You exit the loop, when nextLine == null .nextLine == null时,您退出循环。 Therefore, when you move your println statement out of the loop, nextLine is null .因此,当您将println语句移出循环时, nextLinenull The error "Null pointer access: the variable nextLine can only be null at this location."错误"Null pointer access: the variable nextLine can only be null at this location." makes total sense.完全有道理。

To access everything you read after the loop you could do the following:要访问循环后阅读的所有内容,您可以执行以下操作:

Add this before you enter the loop:在进入循环之前添加以下内容:

List<String[]> readLines = new ArrayList<>();

and in the loop do this:并在循环中执行以下操作:

readLines.add(nextLine);

So after the loop you can read all of your read lines out of the readLines list.因此,在循环之后,您可以从readLines列表中读取所有读取的行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM