填充二维数组
我有一个包含三个人数据的文本文件。每个人的属性以逗号分隔。它看起来像这样:
Patrick, Gary, Male, Blue, 1/28/1948
Carson, Larry, Male, Pink, 11/24/1976
Fisher, Paul, Male, Orange, 5/12/1995
我最终想要完成的任务是按姓氏升序对这些人进行排序。
不确定我是否以正确的方式思考这个问题,但我想创建一个二维数组,将每个属性分配给正确的行和列。我们现在可以忘记排序。
如何让每一行填充数组的一行,每个单独的属性都在其自己的列中?
也许我应该只是逐行读取文件,然后使用 lineFromFile.charAt(index) 来填充或类似的东西将每个字符添加到二维数组中?任何示例建议将不胜感激。
I've got a text file with dats for three people. The properties for each person is separated by a comma. It looks like this:
Patrick, Gary, Male, Blue, 1/28/1948
Carson, Larry, Male, Pink, 11/24/1976
Fisher, Paul, Male, Orange, 5/12/1995
What I'm trying to accomplish ultimately to to sort those people by their last name in ascending order.
Not sure I'm thinking about this the right way, but I wanted to create a 2D array that would assign each property to the proper row and column. We can forget about the sorting for now.
How can I get each line to populate a row of the array, with each separate property in its own column?
Maybe I should just be reading the file line by line, then adding each character to a 2D array using lineFromFile.charAt(index) to populate or something like that? Any sample suggestions would be greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
String.split()
在这里可以提供帮助:但是您可能真正想要的是放弃二维数组的想法并创建一个人员列表,其中 Person 是您定义的类。
二维数组几乎总是表明您需要一个类来表示数据“行”。
排序也变得非常容易:
String.split()
can be of help here:But what you probably really want is to abandon the idea of a 2-D array and create a List of Persons, where Person is a class that you define.
A 2D array almost always suggests that you need a class to represent a "row" of data.
Sorting becomes very easy too:
我建议不要使用二维数组并使用您提到的字段创建一个类(根据@Mark的帖子)。然后创建该类实例的一维数组。
但是,如果您想走二维数组路线:
I would suggest not using a 2D array and creating a class with the fields you mention (per @Mark's post). Then creating a 1D array of instances of that class.
However, if you want to go the 2D array route:
假设您可以获得一个读取器,
您可以使用缓冲读取器逐行读取它,并使用列表来累积行,
然后您可以将列表转换为二维数组。
然后您可以使用自定义比较器对其进行排序。
Assuming you can get a reader
you can read it line by line using a buffered reader and use a list to accumulate the lines
then you can convert the list to a 2-D array.
which you can then sort using a custom comparator.