这是我的代码:

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!");
        System.out.println("Use 'recall' to see your new Diary!");
    } else {
        System.out.println("Very well, returning to first command entry.");
    }
}

最佳答案

看着:

ArrayList<String> readData = new ArrayList<String>();
if (readFileConfirm.equalsIgnoreCase("yes")) {
    for (int i = 0; i < readData.size(); i++) {
        readData.add(reader.nextLine());
    }


您在readLine时调用i < readData,但是readData开始为空,因此循环永远不会运行。您的循环应基于输入,而不是空且可调整大小的ArrayList。看Scanner.hasNextLine

您稍后会有类似的问题:

diary.clear();
for (int i = 0; i < diary.size(); i++) {
    diary.add(readData.get(i));
}


diary.size()从零开始,因此循环将永远不会运行。另外,如果diary是ArrayList,则看起来您可以执行以下操作:

diary = readData;


如果是另一个Collection,则可以执行以下操作:

diary.clear()
diary.addAll(readData);


只需将readData中的所有元素添加到diary

10-08 18:33