-8

I just encounter this in a test that said end the loop if the input is invalid then end the program. My code is like this

    int x=0;
    while(x!=(string)) // this is what I want to know what should i do here
  {
    Console.WriteLine("Input an integer: ");
    x = Int.Parse(Console.ReadLine);
  }
    Console.WriteLine("Invalid input");

What is the proper way to do this?
P.S.
That time, I don't know int.TryParse yet. So I'm exactly looking for a way without using int.TryParse

Wowie
  • 23
  • 9
  • 5
    C# is a strongly-typed language: a variable declared as an int can only ever be an int.. – stuartd Jun 16 '17 at 00:11
  • .. however if you enter something on the console that can't be parsed as an int, then the program **will** end. And not in a nice way. – stuartd Jun 16 '17 at 00:12
  • Yeah I know that good sir, that's why I'm asking how the question in my test should be done properly. :) – Wowie Jun 16 '17 at 00:13
  • What is considered invalid input? As currently written, your code won't even compile. If it *did* compile, it would throw an exception if the input was not a valid integer. That is, `Int.Parse()` would throw an exception if somebody entered "foobar". As it stands, your question is ambiguous enough that I don't know what your code is supposed to do, so I'm not going to try giving an answer. – Jim Mischel Jun 16 '17 at 00:13
  • 3
    Look at the MSDN docs on the `Parse()` and `TryParse()` methods of `Int32` - that should move you in the right direction. – Rick Liddle Jun 16 '17 at 00:13
  • @JimMischel The considered invalid is a string like `foobar` or `b` – Wowie Jun 16 '17 at 00:15
  • I voted to re-open. This question is not a duplicate of "how to convert from string to int." That's *part* of the answer, but clearly not all of it. In particular, the answer to the supposed duplicate was `int.Parse`, which is totally inappropriate here. – Jim Mischel Jun 16 '17 at 00:23

4 Answers4

2

To me, this sounds like a job for a do-while loop with an int.tryparse.

A simple code example of this is as follows:

        string input = string.Empty;

        int x = 0;
        do
        {
            input = Console.ReadLine();
        } while (int.TryParse(input, out x));

        Console.WriteLine("Invalid entry");

        Console.ReadKey();

Do While works similar to a while loop, but it leaves the conditional to the end, which allows for a tryparse at the end.

Tryparse returns a boolean value of true when the value can be successfully parsed as an integer, otherwise, returning false and ending the loop.

Kiradien
  • 104
  • 6
  • 1
    This is a good answer. However, in practice, one will probably want to do something with good values. – Phil1970 Jun 16 '17 at 00:31
2

If you just want to read a string, try to convert to an integer, and exit the program if it's not a valid integer, then you'd use int.TryParse, like this:

string input = Console.ReadLine();
if (int.TryParse(input, out x))
{
    // do something with x
}
else
{
    // input was invalid.
}

If you want to continue doing this in a loop until you got invalid input:

bool validInput = true;
while (validInput == true)
{
    string input = Console.ReadLine();
    int x;
    if (int.TryParse(input, out x))
    {
        Console.WriteLine(x);  // output the integer
    }
    else
    {
        Console.WriteLine("Input was not an integer");
        validInput = false;
    }
}

Update

What, exactly, does your test consider "an integer?" Is it just a string that consists only of one or more digits in the set [0-9]? Or does it need to fit within the C# language's definition of Int32? If the former, then you can use a regular expression to determine if the string is just digits. Otherwise, int.TryParse or int.Parse wrapped in a try ... catch is the way you'll have to do it.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
  • This is the correct answer sir. However, please try to look again in my edited question sir. – Wowie Jun 16 '17 at 01:16
  • I tried this out and it worked. (The second statement). However, please look again in my edited question. – Wowie Jun 16 '17 at 01:19
  • 1
    @Wowie: Well, you could replace `int.TryParse` with a `try / catch` block around `int.Parse`. Or around `Convert.ToInt32`. Either of those will work, although not so elegantly as `int.TryParse`. – Jim Mischel Jun 16 '17 at 02:04
  • Downvoter: If there's something in this answer that you take issue with, it's customary to leave a comment explaining your down vote. – Jim Mischel Jun 16 '17 at 13:13
  • @reds: No, it doesn't accept a Decimal number. The question specifically requested that it accept only integers. – Jim Mischel Jun 20 '17 at 01:20
1

try this:

         Console.WriteLine("About to call Console.ReadLine in a loop.");
        Console.WriteLine("----");
        String s;

        do
        {

            s = Console.ReadLine();
            Regex regex = new Regex("[0-9]");
            Regex regex2 = new Regex("[a-zA-Z]");
            if (regex.IsMatch(s))
            {
                if (regex.IsMatch(s) && regex2.IsMatch(s))
                {
                    Console.WriteLine("You entered an combination of number and String = " + s.ToString());
                }
                else
                {
                    int cnt = s.Count(x => x == '.');
                    if (s.Count(x => x == '.') > 1)
                    {
                        Console.WriteLine("Invalid input of number = " + s.ToString());
                    }
                    else if (s.Count(x => x == '.') == 1 && regex.IsMatch(s))
                    {
                        Console.WriteLine("You entered a decimal number = " + s.ToString());
                    }

                    else
                    {
                        char[] str = "!@#$%^&*()',-./:;<=>?@_`{|}~¡¢£¤¥¦§¨©¬®¯°±²³´µ¶¸¹º»¼½¾¿ÀÈËÌÍÎÏÐÑÒÓÔÕÖרÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõöL÷øùúûüýþÿ\"".ToArray();
                        int indexOf = s.IndexOfAny(str);

                        if (indexOf == -1)
                        {

                            Console.WriteLine("You entered a number = " + s.ToString());

                        }
                        else
                        {
                            Console.WriteLine("You entered an combination of number and String = " + s.ToString());
                        }

                    }

                }
            }
            else
            {
                if (s.Trim().Length < 1)
                {
                    Console.WriteLine("Please enter any value.");
                }
                else
                {
                    Console.WriteLine("You entered a String = " + s.ToString());
                }

            }


        } while (s != null);
        Console.WriteLine("---");
Vijunav Vastivch
  • 4,153
  • 1
  • 16
  • 30
  • Noice! But when I input values like this `w6`, `^6` it outputs an integer. – Wowie Jun 16 '17 at 01:25
  • It will accept and return a correct value even you input a combination of any. – Vijunav Vastivch Jun 16 '17 at 01:43
  • This does not work. In the first place, the value "123.456" is considered an integer. It does not allow for negative integers. Finally, you can eliminate most of your logic with a single statement: `bool isValid = Regex.IsMatch(s, "^[0-9]+$");` If you're going to use regular expressions, at least use them effectively. – Jim Mischel Jun 16 '17 at 02:11
  • Are you sure it doesn't work 123.456 .. i tried it and consider as number.. thanks for your comment.. @Jim Mischel if you have an idea to improve the answer then go ahead edit mine. thanks – Vijunav Vastivch Jun 16 '17 at 03:15
  • Updated the answer.. @Jim Mischel try to run it. – Vijunav Vastivch Jun 16 '17 at 03:28
  • My point is that "123.456" is not an integer. It's a real number. And your code still would allow something like "12)34(", which clearly isn't generally recognized as any kind of number. An integer contains *only* the digits 0 through 9. Possibly a leading sign character (i.e. `-` or '+'). And, no, I don't need to edit your answer; I already supplied one. And, by the way, I think the regular expression `[a-zA-Z_@.-]*` will match every string. The `*` means "zero or more", and every string has zero or more of every character. – Jim Mischel Jun 16 '17 at 04:02
  • I think as tested this is the perfect one. – Vijunav Vastivch Jun 16 '17 at 05:32
  • Your code *does not work*. There are over one million possible Unicode characters, every one of which can be entered by a user at the keyboard. In order for your technique to have any change of working, your string of disallowed characters would have to include all of those, except the digits 0-9. Even now, it misses a few, like the space and tab characters. I already gave you a way to improve your answer,: the regular expression `"^[0-9]+$"`, which matches a string that contains only the digits 0 through 9. – Jim Mischel Jun 16 '17 at 13:26
  • I knew it.. there's a lot of special characters.. but you can add anything if you wish.. how about yours? – Vijunav Vastivch Jun 19 '17 at 23:51
-2

You define X as a int first and the X will always be int-type (),Unless you convert this int type,i think use try{...} catch{...} may be a good way to solve this:

string x;
int result;
while (true)
{
    x = Console.ReadLine();
    try
    {
        result = int.Parse(x);
        Console.WriteLine("int input");
    }
    catch
    {
        Console.WriteLine("Invalid input ");
    }
}

or you can use regular expression like this:

var reg = new Regex("^-?\\d+$");
string result;
Match m;
for (;;)
{
    result = Console.ReadLine();
    m = reg.Match(result);
    if(m.Success)
    {
        Console.WriteLine("int input");
    }
    else
    {
        Console.WriteLine("Invalid input: ");
    }
}
Pang
  • 9,564
  • 146
  • 81
  • 122
  • 1
    Check out `int.TryParse` instead of handling exceptions. Also, you have no way to break out of the loop. Finally, your output when an integer is correctly parsed is wrong. – Jim Mischel Jun 16 '17 at 00:31
  • thank ,in fact ,i know wrong with the word"Invalid",i thought it would be valid,i just know little about english – DUWENINK FERNANDEZ LEE Jun 16 '17 at 00:42