无法找到溢出异常原因 [英] Unable to find overflow exception cause

查看:87
本文介绍了无法找到溢出异常原因的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在本书末尾的练习题中写了以下代码,我正在学习C#。但是,我的代码给了我一个错误,我找不到原因。有人可以查看代码并提出问题区域



I have written the following code to the exercise question given at the end of the book from which I'm learning C#.. However, my code gives me an error and I'm not able to find the reason. Can someone please review the code and mention the problem area

///summary
            ///Write a program, which creates an array containing all Latin letters.
            ///The user inputs a word from the console and as result the program
            ///prints to the console the indices of the characters matching array
            static void Main()
            {
            char ch = 'A';
            char[] alph = new char[26];
            for (int row = 0; row < 26; row++)
            {
                alph[row] = ch;
                ch++;
            }
            for (int row = 0; row < 26; row++)
            {
                Console.Write(alph[row] + " ");
            }
            Console.WriteLine();
            Console.Write("Enter word: ");
            string word = Console.ReadLine();
            string wordUpper = word.ToUpper();
            int wrdIdx = 0;
            for (int i = 0; true; i++)
            {
                if (wordUpper[wrdIdx] == alph[i]) //If below if is removed then this gives as error. Same error of overflow
                {
                    Console.Write(i + " ");
                    wrdIdx++;
                    i = 0;
                    if (wordUpper[wrdIdx] == wordUpper.Length - 1) //This line is giving error if i remove it then the error shows above in the IF statement.
                        break;
                }
            }
            }







这是输出和错误消息我得到:






This is the output and error message that I get:

A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Enter word: Mohit
12 14 7 8 19
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.String.get_Chars(Int32 index)
   at Revision.Program.Main(String[] args) in C:\Users\mohit\source\Revision\Revision\Program.cs:line 632





我尝试过:



试图调试代码。但由于我是初学者,所以无法理解调试器中发生的事情。



我请求提供一个非常基本的答案,而不使用任何外部的东西我已经写了。因为我不太了解各种类和方法提供的其他功能。请尝试仅纠正当前的代码。



请原谅我的英语。



谢谢提前。



What I have tried:

Tried to debug the code. But as I'm a beginner so not able to understand whats going on in the debugger.

I request to please provide a very basic answer without using anything external from what I have written. As i dont know much about other functionalities provided by the various classes and methods. Please try to correct only the current code.

Please also excuse me for my English.

Thanks in advance.

推荐答案

if (wordUpper[wrdIdx] == wordUpper.Length - 1)



wordUpper [wrdIdx] 返回 char ,表示指定索引处的字符。



wordUpper.Length - 1 返回 int - 一号小于字符串的长度。



为了比较它们, char 将转换为Unicode代码点。 (因为您只使用非重音字母,这与其 ASCII 相同[ ^ ]值。)



给定大写输入字符串MOHIT wordUpper [wrdIdx]的数值将是: 77 79 72 73 84 。显然,这些值都不等于 wordUpper.Length - 1 ,所以你的循环永远不会终止。一旦 wrdIdx 超出字符串结尾,当您尝试访问下一个字符时,会得到 IndexOutOfRangeException 。 br />


一个简单的解决方法是使用嵌套循环:


wordUpper[wrdIdx] returns a char representing the character at the specified index.

wordUpper.Length - 1 returns an int - a number one less than the length of the string.

In order to compare them, the char will be converted to its Unicode code-point. (Since you're only working with non-accented letters, this is the same as its ASCII[^] value.)

Given the upper-case input string "MOHIT", the numeric value of wordUpper[wrdIdx] will be: 77, 79, 72, 73 and 84. Obviously, none of those values are equal to wordUpper.Length - 1, so your loop never terminates. Once wrdIdx moves past the end of your string, you get the IndexOutOfRangeException when you try to access the next character.

One simple fix would be to use a nested loop:

foreach (char c in wordUpper)
{
    for (int i = 0; i < alph.Length; i++)
    {
        if (c == alph[i])
        {
            Console.Write(i + " ");
            break;
        }
    }
}


Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
   at System.String.get_Chars(Int32 index)



这不是溢出异常 - 它是一个数组索引异常,它是不同的。

它的含义是 i 大于25,或者 wrdIdx 超过了这个词长度。为什么?因为只有当所有内容都匹配并且它到达 break 语句时才会退出。

我们无法在你做的相同条件下运行你的代码,所以它取决于你。

幸运的是,你有一个工具可以帮助你找到正在发生的事情:调试器。



在函数的第一行放置一个断点,然后通过调试器运行代码。然后查看您的代码,并查看您的数据并找出手动应该发生的事情。然后单步执行每一行检查您预期发生的情况正是如此。如果不是,那就是当你遇到问题时,你可以回溯(或者再次运行并仔细观察)以找出原因。


抱歉,但我们不能为您做到这一点 - 时间让您学习一门新的(非常非常有用的)技能:debugging!


That isn't a "overflow exception" - it's an "array index exception"which is different.
What it's saying is that i is greater that 25, or wrdIdx exceeds the word length. Why? because your loop is only exited if everything matches and it reaches the break statement.
We can't run your code under the same conditions you do, so it's going to be up to you.
Fortunately, you have a tool available to you which will help you find out what is going on: the debugger.

Put a breakpoint on the first line in the function, and run your code through the debugger. Then look at your code, and at your data and work out what should happen manually. Then single step each line checking that what you expected to happen is exactly what did. When it isn't, that's when you have a problem, and you can back-track (or run it again and look more closely) to find out why.

Sorry, but we can't do that for you - time for you to learn a new (and very, very useful) skill: debugging!


错误消息: System.IndexOutOfRangeException:索引超出了数组的范围与数组相关联。数组索引从零开始减去元素数减1.因此,数组中的第一个元素有一个索引0,第二个 - 1,第三个 - 2,......第十个 - 9等等。



查看获取循环以解决您的问题。
An error message: System.IndexOutOfRangeException: Index was outside the bounds of the array is corelated with an array. An array index starts from zero to the count of elements minus 1. So, the first element in array has an index 0, second - 1, third - 2, ... tenth - 9, etc.

Look at your for loops to resolve your issue.


这篇关于无法找到溢出异常原因的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆