[英]Storing strings from a text file/scanner. Array or built-in?
This code snippet is to to read a text file, turn the lines into objects through a different public (non changeable) class(externalClass). 此代码段将读取一个文本文件,通过不同的公共(不可更改)类(externalClass)将这些行变成对象。
The external class does nothing but turn strings (lines from the .txt through nextLine) into objects, and is fully functional. 外部类除了将字符串(从.txt通过nextLine的行)转换为对象外,什么也不做,并且功能齐全。 The scanner(scanner3) is assigned to the text file.
扫描仪(scanner3)被分配给文本文件。
while (scanner3.hasNext()) {
externalClass convertedlines = new externalClass(scanner3.nextLine());
I'm not new to programming, but as I'm new to java, I do not know if this requires me to create an array, or if the returned objects are sorted in some other way. 我对编程并不陌生,但是由于对Java不熟悉,所以我不知道这是否需要我创建数组,或者返回的对象是否以其他方式排序。 ie is the "importedlines" getting overwritten with each run of the loop(and I need to introduce an array into the loop), or are the objects stored in some way?
即,“ importedlines”是否在每次循环运行时都会被覆盖(并且我需要在循环中引入一个数组),或者对象是以某种方式存储的?
The question may seem strange, but with the program I am making it would be harder (but definitely not impossible) if I used an array. 这个问题似乎很奇怪,但是如果使用数组,我正在使程序变得更困难(但绝对不是不可能)。
Any help would be appreciated. 任何帮助,将不胜感激。
As requested, externalClass: 根据要求,externalClass:
public class exernalClass {
private String line;
externalClass(String inLine){
line = inLine;
}
public String giveLine() {
return line;
}
}
You are right, the convertedlines
will be overwritten in every run of the loop. 没错,
convertedlines
行将在循环的每次运行中被覆盖。
Depending on what you want to do with the lines afterwards and if you know how big the files you read are some implementation of Collection
(like an ArrayList
or LinkedList
) may be a better fit than an array. 取决于之后要处理的行以及是否知道读取的文件是
Collection
某种实现(例如ArrayList
或LinkedList
)的大小,它可能比数组更合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.