-1

So I have a bool Variabel called isNumber.

        bool isNumber(string Text)
        {
            bool Answer = true;
            string Number = "1234567890";
            bool ANumber = false;
            for(int j = 0; j <Text.Length; j++)//loop for each char in string Text
            {
                for (int i = 0; i < Number.Length; i++)//loop for each char in the "Number" variable
                {
                    if (Text[j] == Number[i])  //←System.IndexOutOfRangeException: 'Index was outside the bounds of the array.
                    {
                        ANumber = true;
                    }
                }
                if (!ANumber)
                {
                    Answer = false;
                }
            }
            return Answer;
        }

its function is to check a string, if the string is all a number it will return true and return false if there was a non-number char in the string.

but in the loop, there's an error that says indexOutOfRange, but I'm pretty sure it's not. so how do I fix this variable?

or maybe if you have a better working variable to check if a string is a number, lemme know :) thanks for the help. also if you have a suggestion for the title of this forum, just tell me so I will edit the name.

Abibi
  • 38
  • 5
  • 2
    Does this answer your question? [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – Yong Shun Apr 14 '21 at 23:42
  • you can write this function as ```static bool IsNumber(string text) => text.All(c => "1234567890".Contains(c));``` – Keith Nicholas Apr 14 '21 at 23:50
  • Or `IsNumber(string text) => text.All( c => char.IsDigit(c) );` – John Wu Apr 15 '21 at 00:07

2 Answers2

1

You misprinted j with i:

if (Text[j] == Number[i])
Backs
  • 24,430
  • 5
  • 58
  • 85
0
string text = "12345678909876543234a";    

for(int j = 0; j < Text.Length; j++)
{
    if(!char.IsNumber(Text[j]))
    {
        return false;
    }
}
return true;
Syscall
  • 19,327
  • 10
  • 37
  • 52
  • Please, add an explanation. See [how to answer](https://stackoverflow.com/help/how-to-answer). – Syscall Apr 15 '21 at 10:38
  • the computer is checking instead of 10 times (1 for each digit) it will twice ( 47 > char < 58) – Leibel Morozow Apr 15 '21 at 17:58
  • the computer is checking instead of 10 times (1 for each digit {1, 2, 3, 4, 5, 6, 7, 8, 9, 0 } ) it will check only twice( in "Dec" { 47 < char > 58 } ) . – Leibel Morozow Apr 15 '21 at 18:05
  • Please, [edit your answer](https://stackoverflow.com/posts/67100495/edit). It will be more readable than in comments. Thank you. – Syscall Apr 15 '21 at 18:15