You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#控制台日志程序选菜单1后异常退出的修复方案咨询

C#控制台日志程序菜单选项1执行后直接退出的修复方案

问题概述

大一课程项目的C#控制台日志程序,选择菜单选项1(添加条目)后程序直接停止运行,无错误抛出,无法完成添加日志条目的核心功能。

修复要点及代码修改

1. 补全AddEntry方法的核心逻辑

Journal类的AddEntry方法仅收集了日期和内容,但未创建Entry实例并添加到entries列表中,导致程序执行完输入步骤后直接回到循环,但因为没有实际添加数据,看起来像"停止运行"。修改后的AddEntry方法:

//Adds a new entry to the journal from user input
public void AddEntry() {
    string prompt = promptGenerator.GenerateRandomPrompt();
    Console.Write("Please enter the date(mm/dd/yyyy): ");
    string dateInput = Console.ReadLine();
    Console.WriteLine($"Today's Prompt: {prompt}");
    Console.Write("> ");
    string content = Console.ReadLine();
    // 新增:创建Entry实例并添加到列表
    Entry newEntry = new Entry(dateInput, content);
    entries.Add(newEntry);
}

2. 修正PromptGenerator中的字符串语法错误

Prompt列表中有一项末尾多了多余的>符号,可能导致输出异常:
原错误行:

"Write about an act of service you either witnessed or performed today:>",

修改为:

"Write about an act of service you either witnessed or performed today:",

3. 修复LoadFromFile方法的异常输出格式

LoadFromFile方法的异常提示中,文件名占位符使用错误,导致无法正确显示文件名:
原错误行:

Console.WriteLine($"Error loading entries from :filename: {e.Message}");

修改为:

Console.WriteLine($"Error loading entries from {filename}: {e.Message}");

4. 添加缺失的using指令

PromptGenerator和Journal类中使用了List<T>,但未引用System.Collections.Generic命名空间,需在这两个类的开头添加:

using System.Collections.Generic;

修改后验证

完成上述修改后,选择菜单选项1时,程序会正常收集日期和内容,将条目添加到日志列表中,之后可以通过选项2查看条目,选项3/4完成加载/保存操作,程序不会再出现"直接停止"的情况。

内容的提问来源于stack exchange,提问作者Razz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 12:44:53