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

C#列表匹配逻辑异常:else语句触发重复输出错误信息

Hey Carter, let's break down what's going wrong here and fix it step by step.

First, the core issues with your current code are almost certainly these two problems:

  1. You're printing the error message inside your list iteration loop—so every time a list item doesn't match your input, it spits out the error. That's why you see multiple "invalid selection" messages before the correct result: your code is checking each list item one by one and yelling at you for every non-match before finding the right one.
  2. Your loop structure isn't properly controlling when to repeat the input flow, leading to the error message continuing to print even after a valid selection is made.

Here's a fixed implementation that meets your requirements (no arrays, proper matching, single error per invalid input):

using System;
using System.Collections.Generic;

class WeddingRingSelector
{
    static void Main()
    {
        // Use a List instead of an array (satisfies your "no array" rule)
        List<string> validGemstones = new List<string> { "diamond", "ruby", "sapphire", "emerald" };
        bool isSelectionValid = false;
        string userInput = string.Empty;

        // Loop until we get a valid selection
        while (!isSelectionValid)
        {
            Console.WriteLine("Please enter a gemstone for your wedding ring:");
            // Normalize input to avoid case sensitivity and whitespace issues
            userInput = Console.ReadLine()?.ToLower().Trim() ?? string.Empty;

            // Check if input exists in our valid list (clean, built-in method)
            isSelectionValid = validGemstones.Contains(userInput);

            if (isSelectionValid)
            {
                // Success: only runs once when a match is found
                Console.WriteLine($"Your wedding ring will feature your selection: {userInput}");
            }
            else
            {
                // Error: only runs once per invalid input attempt
                Console.WriteLine("I'm sorry that was not a valid selection.");
            }
        }
    }
}

If you need to manually iterate through the list (instead of using Contains()):

Maybe you have custom logic per list item that requires manual checking—here's how to do that without spamming error messages:

using System;
using System.Collections.Generic;

class WeddingRingSelector
{
    static void Main()
    {
        List<string> validGemstones = new List<string> { "diamond", "ruby", "sapphire", "emerald" };
        bool isSelectionValid = false;
        string userInput = string.Empty;

        while (!isSelectionValid)
        {
            Console.WriteLine("Please enter a gemstone for your wedding ring:");
            userInput = Console.ReadLine()?.ToLower().Trim() ?? string.Empty;

            isSelectionValid = false;
            // Check each item in the list manually
            foreach (string stone in validGemstones)
            {
                if (stone == userInput)
                {
                    isSelectionValid = true;
                    break; // Exit the loop immediately when we find a match
                }
            }

            // Handle success/error AFTER checking all list items
            if (isSelectionValid)
            {
                Console.WriteLine($"Your wedding ring will feature your selection: {userInput}");
            }
            else
            {
                Console.WriteLine("I'm sorry that was not a valid selection.");
            }
        }
    }
}

Key fixes to remember:

  • Don't print errors inside your list loop: Always wait until you've checked all items, then use a boolean flag to decide whether to show an error once.
  • Normalize user input: Lowercasing and trimming whitespace prevents issues like "Diamond" or " diamond " being treated as invalid.
  • Control the outer loop properly: Use a boolean flag to keep the input prompt running only until a valid selection is made.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:52:55