Home > Blockchain >  Problem with a while loop in C# - returns multiple
Problem with a while loop in C# - returns multiple

Time:01-09

I am new to C# (1 week in) and I have been scratching my head with no answers. Simply put this is part of a text based game out of much larger file. The player has the option to accept or decline an incoming call. If y/Y or n/N is entered all is well. If I purposely enter an incorrect character the while loop will print "Please respond with 'Y' or 'N' only.." 3 times. I cannot work out why. If you enter 2 letters such as GG it will print it 4 times, 3 letters, 5 times and so on. I know this is an easy fix, I just need someone to point out what I've done wrong.

//INCOMING CALL
static void IncomingCall(char rawResponse)
{
    // Convert response to upper
    // (note method as ToUpper cannot be called conventionally on type char)
    char response = char.ToUpper(rawResponse);
    while (response != 'Y' && response != 'N')
    {
        WriteLine("Please respond with 'Y' or 'N' only..");
        rawResponse = (char)Read();
        response = char.ToUpper(rawResponse);
    }
}
//called in main elsewhere in the file..
WriteLine("Incoming call from Tony. Press 'Y' to accept or 'N' to decline.");
char getInput = (char)Read();
IncomingCall(getInput);

CodePudding user response:

I solved it, with your help by changing method to accept string and use ReadLine()

Changed

(response != 'Y' && response != 'N')

To

(response != "Y" && response != "N")

I did not realise '' and "" produce different results. I am used to Python. Thanks for the input guys.

CodePudding user response:

I suggest changing the design. Let's implement ReadBool methods which incapsulates all the logic of bool value input:

    public static bool ReadBool(string title) {
      // We keep asking user until valid (N or Y) value is entered
      while (true) {
        // If we have a title, let's show it 
        if (!string.IsNullOrWhiteSpace(title))
          Console.WriteLine(title);

        // User has to press 'Y' or 'N'; no need for enter
        var key = Console.ReadKey();

        if (key.KeyChar == 'Y')
          return true;
        if (key.KeyChar == 'N')
          return false;

        // Invalid value; let user know it and try again
        Console.WriteLine("Please respond with 'Y' or 'N' only..");
      }
    }

Possible usage:

bool acceptTony = ReadBool("Incoming call from Tony. Press 'Y' to accept or 'N' to decline.");

if (acceptTony) {
  Console.WriteLine("Hi Tony!");
  //TODO: put relevant code here
}
else {
  Console.WriteLine("Declined");
  //TODO: put relevant code here
}

CodePudding user response:

Swap Read() with Console.Readline()[0];.

EDIT: Or change your method signature to be a string and leverage Console.Readline() as stated in the comments prior.

  •  Tags:  
  • Related