java - How do you create an array list of objects from a text file and have each object be an array in java?
问题描述
How would you be able to import a .txt file and then place each line into an array list as an object, but have each object be an array.
The .txt file looks like this:
1 a 1 2
1 b 0 1
2 a 2 3
2 b 0 3
3 a 3 1
3 b 0 3
I wanted to be able to make each line an object array like so where so that i could call upon the object and the specific point in the array:
<1,a,1,2>
<1,b,0,1>
<2,a,2,3>
<2,b,0,3>
<3,a,3,1>
<3,b,0,3>
and then have an array list where each line (there can be any amount of line hence why i chose an array list) is one thing in the array list. kinda like <line1,line2,line3,etc..>
so i can use the array list and then the values in the individual arrays within the array list.
This is the code that I currently have and i don't know where to go from here. I am using a buffered reader
Scanner input = new Scanner(System.in); // Create a Scanner object
String inputString = input.nextLine();
try {
BufferedReader FSMreader = new BufferedReader(new FileReader(args[0]));
List<FSMline> line = new ArrayList<>();
List<String> currentState = new ArrayList<>();
List<String> inputChoice = new ArrayList<>();
List<String> outputFunction = new ArrayList<>();
List<String> nextState = new ArrayList<>();
String lines;
while ((lines = FSMreader.readLine()) != null) {
line.add(new FSMline(lines.split(" ")));
}
Any help is appreciated because i'm running out of time on a deadline in a class that i am struggling to understand.
thanks
解决方案
Because you didn't mention the datatype of FSMline
, I create a collection(array list of arrays) - List<String[]>
- to store the content of given text file as follows:
BufferedReader fsmReader = new BufferedReader(new FileReader(args[0]));
List<String[]> contentList = new ArrayList<>();
String lines;
while ((lines = fsmReader.readLine()) != null) {
contentList.add(lines.split(" "));
}
//print the list
for (String[] content : contentList) {
System.out.println(Arrays.toString(content));
}
Console output:
[1, a, 1, 2]
[1, b, 0, 1]
[2, a, 2, 3]
[2, b, 0, 3]
[3, a, 3, 1]
[3, b, 0, 3]
UPDATED
And if you want to get the third element of first array in the array list, please use get(int index)
and [int index]
to retrieve element from list and array, respectively:
System.out.println(contentList.get(0)[2]);
Or, you can transform an array into a list by using Arrays.asList()
, then you can also use get(int index)
:
System.out.println(Arrays.asList(contentList.get(0)).get(2));
推荐阅读
- c# - 当实例化一个 Prefab 的多个 GameObjects 时,只有最后一个创建的按钮起作用
- c# - 我有一个统一项目,我在其中使用颜色,但我需要一些帮助
- javascript - 强制刷新和清除缓存 - ReactJS
- python - pycharm 编码错误信息。numpy.ndarray
- angular - 仅针对一个用户的随机 CORS 预检问题
- javascript - NextJS | getStaticProps 在构建时失败
- websocket - 三星电视复制权限 Websocket
- android - 初始化提供程序时 Firebase 身份验证崩溃(Android)
- c# - 如何强制 Odata 使用我的自定义 DTO 对象?
- mysql - Rails has_many 基于 json 数组列