ArrayList 内容超出范围,并在 Java 中的 While 循环后删除
ArrayList contents Out of Scope, and deleted, after a While Loop in Java
我正在尝试使用 while 循环将列表列表保存到 ArrayList,该循环在扫描仪中的行上循环。扫描仪正在读取一个 12 行的二进制文本文件。列表列表(ArrayList)创建成功,但是一旦while循环终止变量ArrayList为空,返回一个空的列表列表。我还通过在声明列表列表的同时声明一个计数器来测试代码,并且计数器在 while 循环中递增并在循环后保留数据。
我对编码还是很陌生!提前谢谢你。
public static void main(String[] args) throws Exception{
try {
readFile();
data = dataPrep();
}
catch (Exception e) {
e.printStackTrace ();
}
}
public static void readFile() throws FileNotFoundException {
try {
File inputtxt = new File("test.txt");
scanner = new Scanner(inputtxt);
}
catch (FileNotFoundException error) {
System.out.println(error);
}
}
public static ArrayList<ArrayList> dataPrep(){
ArrayList<ArrayList> allBinaryNumbers = new ArrayList<ArrayList>();
ArrayList<Integer> singleBinaryNumber = new ArrayList<Integer>();
int counter = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
char[] charLine = line.toCharArray();
for (char numb : charLine){
singleBinaryNumber.add(Integer.parseInt(String.valueOf(numb)));
}
allBinaryNumbers.add(singleBinaryNumber);
System.out.println(allBinaryNumbers);
singleBinaryNumber.clear();
counter++;
}
System.out.println(allBinaryNumbers);
System.out.println(counter);
return allBinaryNumbers;
}
我的test.txt是这个
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
您正在重复使用完成填充后清除的同一个 singleBinaryNumber
。请记住,这是一个 reference(指针),这意味着您在每次迭代中添加相同的列表而不是新列表。
你的代码应该是这样的:
public static ArrayList<ArrayList> dataPrep(){
ArrayList<ArrayList> allBinaryNumbers = new ArrayList<ArrayList>();
int counter = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
char[] charLine = line.toCharArray();
ArrayList<Integer> singleBinaryNumber = new ArrayList<Integer>(); // create a new list for each iteration
for (char numb : charLine){
singleBinaryNumber.add(Integer.parseInt(String.valueOf(numb)));
}
allBinaryNumbers.add(singleBinaryNumber);
System.out.println(allBinaryNumbers);
// singleBinaryNumber.clear(); <-- remove this line
counter++;
}
System.out.println(allBinaryNumbers);
System.out.println(counter);
return allBinaryNumbers;
}
我认为更好的方法是让 readFile()
方法做到这一点,读取文件而不是仅仅打开它,并让这个方法 return 一个 ArrayList。它还应该接受一个字符串参数,该参数将是文件路径(带有文件名),而不是直接在方法本身中对文件路径进行硬编码,例如:
// Class instance member variable with Getter & Setter methods.
private String sourceFile;
// In your main() method:
// List of Lists. Each internal list is from a different file.
List<List<String>> filesBinaries = new ArrayList<>();
// List for current file to be read.
List<String> binaries = readFile(sourceFile);
// Add the current file List object to the
// List of Lists (filesBinaries).
if (!binaries.isEmpty()) {
filesBinaries.add(binaries);
}
这样,您的 readFile()
方法可能看起来像这样:
public static List<String> readFile(String filePath) throws FileNotFoundException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException("readFile() Method Error! The "
+ "supplied file in the path shown below does not exist!" + System.lineSeparator()
+ file.getAbsolutePath() + System.lineSeparator());
}
List<String> binaryLines = new ArrayList<>();
// 'Try With Resources' is used here to auto-close the reader.
try (Scanner reader = new Scanner(file)) {
String line = "";
while (reader.hasNextLine()) {
line = reader.nextLine().trim();
// Data Line Validation:
/* Skip past blank lines (if any) and any lines
that do not contain a valid binary string. Valid
lines would be: 100100 or 00100 11100 01110 */
if (line.isEmpty() || !line.matches("[01 ]+")) {
continue;
}
binaryLines.add(line);
}
}
return binaryLines;
}
要触发此方法,您的 main()
方法可能如下所示:
public static void main(String[] args) {
List<List<String>> filesData = new ArrayList<>();
String sourceFile = "BinaryData.txt"; // The CURRENT file to read
try {
// Read the desired file...
List<String> binaryData = readFile(sourceFile);
// If the binaryData list is not empty then add it to the fileData List.
if (!binaryData.isEmpty()) {
filesData.add(binaryData);
}
}
catch (FileNotFoundException ex) {
System.err.println("The file: \"" + sourceFile + "\" could not be "
+ "found!" + System.lineSeparator() + ex.getMessage());
}
// Display the contens of the filesData List...
for (int i = 0; i < filesData.size(); i++) {
System.out.println("File #" + (i + 1) + " Binary Data:");
System.out.println("====================");
for (String binaryString : filesData.get(i)) {
System.out.println(binaryString);
}
}
}
我正在尝试使用 while 循环将列表列表保存到 ArrayList,该循环在扫描仪中的行上循环。扫描仪正在读取一个 12 行的二进制文本文件。列表列表(ArrayList)创建成功,但是一旦while循环终止变量ArrayList为空,返回一个空的列表列表。我还通过在声明列表列表的同时声明一个计数器来测试代码,并且计数器在 while 循环中递增并在循环后保留数据。
我对编码还是很陌生!提前谢谢你。
public static void main(String[] args) throws Exception{
try {
readFile();
data = dataPrep();
}
catch (Exception e) {
e.printStackTrace ();
}
}
public static void readFile() throws FileNotFoundException {
try {
File inputtxt = new File("test.txt");
scanner = new Scanner(inputtxt);
}
catch (FileNotFoundException error) {
System.out.println(error);
}
}
public static ArrayList<ArrayList> dataPrep(){
ArrayList<ArrayList> allBinaryNumbers = new ArrayList<ArrayList>();
ArrayList<Integer> singleBinaryNumber = new ArrayList<Integer>();
int counter = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
char[] charLine = line.toCharArray();
for (char numb : charLine){
singleBinaryNumber.add(Integer.parseInt(String.valueOf(numb)));
}
allBinaryNumbers.add(singleBinaryNumber);
System.out.println(allBinaryNumbers);
singleBinaryNumber.clear();
counter++;
}
System.out.println(allBinaryNumbers);
System.out.println(counter);
return allBinaryNumbers;
}
我的test.txt是这个
00100
11110
10110
10111
10101
01111
00111
11100
10000
11001
00010
01010
您正在重复使用完成填充后清除的同一个 singleBinaryNumber
。请记住,这是一个 reference(指针),这意味着您在每次迭代中添加相同的列表而不是新列表。
你的代码应该是这样的:
public static ArrayList<ArrayList> dataPrep(){
ArrayList<ArrayList> allBinaryNumbers = new ArrayList<ArrayList>();
int counter = 0;
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
char[] charLine = line.toCharArray();
ArrayList<Integer> singleBinaryNumber = new ArrayList<Integer>(); // create a new list for each iteration
for (char numb : charLine){
singleBinaryNumber.add(Integer.parseInt(String.valueOf(numb)));
}
allBinaryNumbers.add(singleBinaryNumber);
System.out.println(allBinaryNumbers);
// singleBinaryNumber.clear(); <-- remove this line
counter++;
}
System.out.println(allBinaryNumbers);
System.out.println(counter);
return allBinaryNumbers;
}
我认为更好的方法是让 readFile()
方法做到这一点,读取文件而不是仅仅打开它,并让这个方法 return 一个 ArrayList。它还应该接受一个字符串参数,该参数将是文件路径(带有文件名),而不是直接在方法本身中对文件路径进行硬编码,例如:
// Class instance member variable with Getter & Setter methods.
private String sourceFile;
// In your main() method:
// List of Lists. Each internal list is from a different file.
List<List<String>> filesBinaries = new ArrayList<>();
// List for current file to be read.
List<String> binaries = readFile(sourceFile);
// Add the current file List object to the
// List of Lists (filesBinaries).
if (!binaries.isEmpty()) {
filesBinaries.add(binaries);
}
这样,您的 readFile()
方法可能看起来像这样:
public static List<String> readFile(String filePath) throws FileNotFoundException {
File file = new File(filePath);
if (!file.exists()) {
throw new FileNotFoundException("readFile() Method Error! The "
+ "supplied file in the path shown below does not exist!" + System.lineSeparator()
+ file.getAbsolutePath() + System.lineSeparator());
}
List<String> binaryLines = new ArrayList<>();
// 'Try With Resources' is used here to auto-close the reader.
try (Scanner reader = new Scanner(file)) {
String line = "";
while (reader.hasNextLine()) {
line = reader.nextLine().trim();
// Data Line Validation:
/* Skip past blank lines (if any) and any lines
that do not contain a valid binary string. Valid
lines would be: 100100 or 00100 11100 01110 */
if (line.isEmpty() || !line.matches("[01 ]+")) {
continue;
}
binaryLines.add(line);
}
}
return binaryLines;
}
要触发此方法,您的 main()
方法可能如下所示:
public static void main(String[] args) {
List<List<String>> filesData = new ArrayList<>();
String sourceFile = "BinaryData.txt"; // The CURRENT file to read
try {
// Read the desired file...
List<String> binaryData = readFile(sourceFile);
// If the binaryData list is not empty then add it to the fileData List.
if (!binaryData.isEmpty()) {
filesData.add(binaryData);
}
}
catch (FileNotFoundException ex) {
System.err.println("The file: \"" + sourceFile + "\" could not be "
+ "found!" + System.lineSeparator() + ex.getMessage());
}
// Display the contens of the filesData List...
for (int i = 0; i < filesData.size(); i++) {
System.out.println("File #" + (i + 1) + " Binary Data:");
System.out.println("====================");
for (String binaryString : filesData.get(i)) {
System.out.println(binaryString);
}
}
}