How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Delphi programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Delphi programming language

Table of Contents

Problem Statement

Obtain a valid   Y   or   N   response from the keyboard. The keyboard should be flushed, so that any outstanding key-presses are removed, preventing any existing   Y   or   N   key-press from being evaluated. The response should be obtained as soon as   Y   or   N   are pressed, and there should be no need to press an   enter   key.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Keyboard input/Obtain a Y or N response step by step in the Delphi programming language

Source code in the delphi programming language

program Obtain_a_Y_or_N_response;

{$APPTYPE CONSOLE}

uses
  System.Console;

function GetKey(acepted: string): Char;
var
  key: Char;
begin
  while True do
  begin
    if Console.KeyAvailable then
    begin
      key := UpCase(Console.ReadKey().KeyChar);
      if pos(key, acepted) > 0 then
        exit(key);
    end;
  end;
  Result := #0; // Never Enter condition
end;

begin
  Console.WriteLine('Press Y or N');
  case GetKey('YN') of
    'Y':
      Console.WriteLine('You pressed Yes');
    'N':
      Console.WriteLine('You pressed No');
  else
    Console.WriteLine('We have a error');
  end;
  Readln;
end.


  

You may also check:How to resolve the algorithm Quine step by step in the Prolog programming language
You may also check:How to resolve the algorithm Maze generation step by step in the REXX programming language
You may also check:How to resolve the algorithm Non-decimal radices/Input step by step in the PowerShell programming language
You may also check:How to resolve the algorithm Handle a signal step by step in the Gambas programming language
You may also check:How to resolve the algorithm S-expressions step by step in the Python programming language