【问题标题】:What's wrong with this while condition? [duplicate]这个while条件有什么问题? [复制]
【发布时间】:2018-04-06 00:12:09
【问题描述】:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        public const int N = 10;
        static void Main(string[] args)
        {
            char[] word = Console.ReadLine().ToCharArray();
            int i = 0, j = 0;
            Console.WriteLine(word);
            while ((word[i] >= 'a' && word[i] <= 'z') || (word[i] >= 'A' && word[i] <= 'Z'))
            {
                j++;
                i++;
            }
            Console.WriteLine(+j);
            Console.ReadLine();

        }
    }
}

每次我尝试调试时,调试器都会告诉我“IndexOutOfRangeException was unhandled”,我不知道原因。

【问题讨论】:

  • 您永远不会检查 word 数组的长度。如果所有字符都是字母,则循环将继续,直到i 超出数组末尾,然后您将得到异常。
  • 提示:在提问之前,请确保搜索错误消息/异常名称(如 bing.com/search?q=c%23+IndexOutOfRangeException),如果您仍然决定提问,请遵循 minimal reproducible example 指南以提供包含所有必要信息的最少代码内联(即在本例中为 "A".ToCharArray()[1]")

标签: c# arrays string while-loop conditional-statements


【解决方案1】:

您只是没有检查数组的长度并不断检查导致IndexOutOfRangeException 的元素

添加此条件,它将起作用

while (i < word.Length && (word[i] >= 'a' && word[i] <= 'z') || (word[i] >= 'A' && word[i] <= 'Z'))
{
   j++;
   i++;
}

您还应该知道为什么会抛出IndexOutOfRangeException 以及它的含义是什么-https://msdn.microsoft.com/en-us/library/system.indexoutofrangeexception(v=vs.110).aspx

【讨论】:

    【解决方案2】:

    这是因为您在 while 循环的每次迭代中递增 ij,但您永远不会退出循环。

    char[] word = Console.ReadLine().ToCharArray();
    

    i 的值大于从控制台读取的行时会发生什么?你得到IndexOutOfRangeException

    也许想想你什么时候想停止增加i,然后跳出循环。

    【讨论】:

    • ..这个问题有家庭作业的味道..我已经相应地回答了,只是没有提供解决方案,而是让发布者考虑如何解决。
    【解决方案3】:

    以上答案已经提供了有关该问题的足够信息。我想我只会添加结果。

    如果您只想显示字母,只需检查输入的字母/单词是字母字符还是空格,然后显示字母/单词,否则返回无效的错误消息。

    这是完整的测试类供您参考。

    using System;
    using System.Text.RegularExpressions;
    
    namespace WhileLoop
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                string words = Console.ReadLine();
    
                //input words
                Console.WriteLine(words);
    
    
                //check not alphabet or space, return invalid error message
                Regex rgx = new Regex("[^a-zA-Z ]+");
                if (rgx.IsMatch(words))
                {
                    Console.WriteLine("Please input alphabet or space only Ie. A-Z, a-z,");
                }
    
                Console.ReadLine();
    
            }
        }
    }
    

    场景#1 - 输入非字母字符

    场景#2 - 输入字母字符和空格(预期结果)

    【讨论】:

    • OPs 代码计算字符串中前导字母字符的数量,但这也很有趣。
    猜你喜欢
    • 2011-02-06
    • 2014-11-26
    • 2011-01-25
    • 2014-02-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多