Question Need help with do..while...

GhostCavalry

New member
Joined
Jan 11, 2017
Messages
1
Programming Experience
Beginner
Hello!
I need your help with Do & While.

When I debug the code and input a whitespace for the first time it shows "Input is invalid".
But when I input a legit string for the second time it shows me "Input is Invalid" and proceeds to the Readkey method.
How can I fix this?

Here is the code:
C#:
[COLOR=#0000ff]public static void[/COLOR] Main(string[] args)
        {
            Test();
            Console.ReadKey();
        }

[COLOR=#0000ff]static void[/COLOR] Test()        
{
            [COLOR=#0000cd]string [/COLOR]SString;
            SString = [COLOR=#0000cd]Console[/COLOR].ReadLine();
            if ([COLOR=#0000cd]string[/COLOR].IsNullOrWhiteSpace(SString))
            {
                [COLOR=#0000cd]Console[/COLOR].WriteLine("Input is Invalid");
                [COLOR=#0000cd]do[/COLOR]
                {
                    SString = [COLOR=#0000cd]Console[/COLOR].ReadLine();
                    [COLOR=#0000cd]Console[/COLOR].WriteLine("Input is Invalid");
                } [COLOR=#0000cd]while [/COLOR]([COLOR=#0000ff]string[/COLOR].IsNullOrWhiteSpace(SString));
            } 
            [COLOR=#0000cd]else [/COLOR]
            {
                [COLOR=#0000cd]Console[/COLOR].WriteLine("Ok!");
            }

Thanks in advance!
 
Have you debugged your code? If not then do so. Place a breakpoint at the top of the code and then step through it line by line. At each step, you can assess the application state and then you'll know exactly when that state doesn't match your expectation and exactly what the difference is. You should likely be able to determine the reason too but, if you can't, at least you'll be able to give us all the relevant information.
 
SString = Console.ReadLine();
Console.WriteLine("Input is Invalid");
Here you get input, and immediately write "Input is Invalid".

Try this (pseudo code)
C#:
declare and set 'input' variable to empty string
while (string.IsNullOrWhiteSpace(input))
{
     write "input something, not whitespace"
     get input (ReadLine)
}
write "input ok"
 
Back
Top Bottom