-1

I am currently working on a project and I have already created an arraylist within my program. However, I am now trying to import the list from an external inotepad file so I can simply change the contents of the file instead adding new lines into the program itself. I've attempted to use a scanner to pull the list but it doesn't seem as if I am doing it correctly. The examples I am finding online show using a scanner, but I don't know how I can translate it into an existing array. I could definitely use some guidance!

Program:

package animalNames;

import java.util.*;
public class animalList {

public static void main(String args[]) {
// Create a new array list
ArrayList animalNames = new ArrayList();

// add animals to the array list
animalNames.add("Aligator");
animalNames.add("Rabbit");
animalNames.add("Snake");
animalNames.add("Spider");
animalNames.add("Turtle");
animalNames.add("Dog");

// Allow iterator to show contents of array list
System.out.print("Animals kept at the zoo: ");
Iterator itr = animalNames.iterator();

while(itr.hasNext()) {
    Object element = itr.next();
    System.out.print(element + " ");
}
System.out.println();

// Change the contents within array list
ListIterator litr = animalNames.listIterator();

while(litr.hasNext()) {
    Object element = litr.next();
    litr.set("1 " + element + " ");
}
System.out.print("There is exactly: ");
itr = animalNames.iterator();

while(itr.hasNext()) {
    Object element = itr.next();
    System.out.print(element);
}
System.out.println();

// Display array list backwards
System.out.print("Display list backward: ");

while(litr.hasPrevious()) {
    Object element = litr.previous();
    System.out.print(element + " ");
}
System.out.println();
}

}

GhostCat
  • 127,190
  • 21
  • 146
  • 218

2 Answers2

0

The point is: when reading data from a file, there is no "existing" array.

In other words:

  • your use case is: you hard code a List (which is not the same as an array), and then iterate over that content
  • when using data from a file, you read the file, and put that content into a previously empty list

You can find extensive explanations how to do that using a Scanner here for example.

Please understand: there are no detours. You have to step back and study such tutorials until you understand what they do. We can't explain such things in one sentence to you. It simply takes the time that it takes ...

Community
  • 1
  • 1
GhostCat
  • 127,190
  • 21
  • 146
  • 218
0

To read from a file and populate a List, this will work.

List<String> lines = Files.readAllLines(Paths.get("file_path"), StandardCharsets.UTF_8);

rslj
  • 179
  • 2
  • 10