why isn't the input text file being read into the ArrayList<String>, diary?
Here's my code:
public void readFile() throws IOException {
System.out.println("Input file name: ");
Scanner in = new Scanner(System.in);
String readName = in.nextLine();
Scanner reader = new Scanner(new File(readName));
System.out.println("Reading file...");
while (reader.hasNextLine()) {
System.out.println(reader.nextLine());
}
System.out.println("File read.");
Scanner inAgain = new Scanner(System.in);
System.out.println("Would you like to read this into the current Diary?");
System.out.println("Warning: This will overwrite your current Diary!");
String readFileConfirm = inAgain.nextLine();
ArrayList<String> readData = new ArrayList<String>();
if (readFileConfirm.equalsIgnoreCase("yes")) {
for (int i = 0; i < readData.size(); i++) {
readData.add(reader.nextLine());
}
System.out.println("Data added to extra array...");
System.out.println("Here are the contents.");
for (int i = 0; i < readData.size(); i++) {
System.out.println(readData.get(i));
}
System.out.println("Contents read.");
System.out.println("Now overwriting current Diary with read file...");
diary.clear();
for (int i = 0; i < diary.size(); i++) {
diary.add(readData.get(i));
}
System.out.println("New Diary created!");
Syst开发者_StackOverflow中文版em.out.println("Use 'recall' to see your new Diary!");
} else {
System.out.println("Very well, returning to first command entry.");
}
}
Look at:
ArrayList<String> readData = new ArrayList<String>();
if (readFileConfirm.equalsIgnoreCase("yes")) {
for (int i = 0; i < readData.size(); i++) {
readData.add(reader.nextLine());
}
You're calling readLine
while i < readData
, but readData
starts empty so the loop never runs. Your loop should be based on the input, not the empty and resizable ArrayList. Look at Scanner.hasNextLine
.
You have a similar issue later:
diary.clear();
for (int i = 0; i < diary.size(); i++) {
diary.add(readData.get(i));
}
diary.size()
starts at zero, so the loop will never run. Also, if diary
is an ArrayList, it looks like you can just do:
diary = readData;
If it's another Collection
, you can do:
diary.clear()
diary.addAll(readData);
That will simply add all the elements in readData
to diary
.
精彩评论