'Change the amount of times code checks number
Console.Write("Enter -");
string input = Convert.ToString(Console.ReadLine());
string ascii = input;
byte[] ASCIIValues = Encoding.ASCII.GetBytes(ascii);
for (int i = 0; i < input.Length; i++)
{
if (ASCIIValues[i] >= 48 && ASCIIValues[i] <= 57)
{
Console.WriteLine("Is number");
}
else
{
Console.WriteLine("Is not number");
}
}
I have made a code where it checks if you have entered number or not. It works fine while using only numbers from 1 to 9 . When I enter number with more digits the code checks each number. For example I enter 100 , and the code shows 3 lines "Is number." How could I change it , to only showing 1 line of "Is number."
Solution 1:[1]
Thats very complicated code for such a simple task
Console.Write("Enter -");
string input = Console.ReadLine();
if(input.All(c=>Char.IsDigit(c)))
Console.WriteLine("Is number");
else
Console.WriteLine("Is not a number");
or you could do this (since the next thing I expect you to do is convert that input to a number)
Console.Write("Enter -");
string input = Console.ReadLine();
int num;
if (Int32.TryParse(input, out num))
Console.WriteLine("is a number");
else
Console.WriteLine("is not a number");
TryParse tries to convert the string to a number and reports success or failure
Solution 2:[2]
You are reading each char in the whole string and printing the result for each char... To follow your approach you should be checking the whole string first and print a positive result only if all char check was verified as a number.
Try something like this:
// ... your previous code
bool result = true;
for (int i = 0; i < input.Length; i++)
if (ASCIIValues[i] >= 48 && ASCIIValues[i] <= 57)
continue;
else
{
result = false;
break;
}
if (result == true)
Console.WriteLine("Is number");
else
Console.WriteLine("Is not number");
Here I'm initializing a bool variable result with true value. If the code runs until the end of the loop with no break call, it would be considered a number. Otherwise, it would be false
Note: the char.IsNumber(char inputChar) function is a System's library function that does something like what you did with ASCII code checks. Using it, your code should look like this:
public static bool IsNumeric(string input)
{
if(input.Length == 0)
return false;
for(int i = 0; i <input.Length; i++)
if(!char.IsNumber(input[i]))
return false;
return true;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | pm100 |
| Solution 2 | Diego Rafael Souza |
