C#控制台程序Console.WriteLine提前输出问题及代码修正请求
修正C#控制台商品查询程序的输入输出逻辑问题
你的代码核心问题是在for循环内部提前调用了Console.ReadLine(),导致输入读取和商品遍历的逻辑混乱——还没完成当前输入的匹配查找,就提前读取了下一个输入,进而出现输出时机错误、提前打印的情况。
以下是保留变量a输出逻辑的修正代码:
using System; using System.Collections.Generic; using System.Linq; namespace List.Store { class Program { static void Main(string[] args) { string name = Console.ReadLine(); string quantity = Console.ReadLine(); string price = Console.ReadLine(); List<string> names = name.Split(" ").ToList(); List<long> quantities = quantity.Split(" ").Select(long.Parse).ToList(); List<double> prices = price.Split(" ").Select(double.Parse).ToList(); string input = Console.ReadLine(); while(input != "done") { // 遍历商品列表,用变量a作为索引查找匹配项 for (int a = 0; a < names.Count; a++) { if (names[a] == input) { // 对齐期望输出的格式,补充costs后的冒号 Console.WriteLine($"{input} costs: {prices[a]}; Available quantity: {quantities[a]}"); break; // 找到匹配项后终止遍历,提升效率 } } // 完成当前输入的查询后,再读取下一个输入 input = Console.ReadLine(); } } } }
关键修改说明
- 把
input = Console.ReadLine();从for循环内部移到while循环末尾,确保每次完整处理完当前商品查询后,再读取下一个输入,避免逻辑错位。 - 找到匹配商品后添加
break;,无需继续遍历剩余商品(可选优化)。 - 调整输出字符串格式,和你给出的期望输出对齐(原代码缺少
costs后的冒号)。
运行修正后的代码,输入测试内容后会得到符合预期的输出:
Bread costs: 2.34; Available quantity: 10 Juice costs: 1.23; Available quantity: 50
内容的提问来源于stack exchange,提问作者Martin Kulev
相关产品推荐
相关产品推荐

