How to resolve the algorithm Menu step by step in the D programming language
Published on 12 May 2024 09:40 PM
How to resolve the algorithm Menu step by step in the D programming language
Table of Contents
Problem Statement
Given a prompt and a list containing a number of strings of which one is to be selected, create a function that:
The function should reject input that is not an integer or is out of range by redisplaying the whole menu before asking again for a number. The function should return an empty string if called with an empty list. For test purposes use the following four phrases in a list: This task is fashioned after the action of the Bash select statement.
Let's start with the solution:
Step by Step solution about How to resolve the algorithm Menu step by step in the D programming language
Source code in the d programming language
import std.stdio, std.conv, std.string, std.array, std.typecons;
string menuSelect(in string[] entries) {
static Nullable!(int, -1) validChoice(in string input,
in int nEntries)
pure nothrow {
try {
immutable n = input.to!int;
return typeof(return)((n >= 0 && n <= nEntries) ? n : -1);
} catch (Exception e) // Very generic
return typeof(return)(-1); // Not valid.
}
if (entries.empty)
return "";
while (true) {
"Choose one:".writeln;
foreach (immutable i, const entry; entries)
writefln(" %d) %s", i, entry);
"> ".write;
immutable input = readln.chomp;
immutable choice = validChoice(input, entries.length - 1);
if (choice.isNull)
"Wrong choice.".writeln;
else
return entries[choice]; // We have a valid choice.
}
}
void main() {
immutable items = ["fee fie", "huff and puff",
"mirror mirror", "tick tock"];
writeln("You chose '", items.menuSelect, "'.");
}
You may also check:How to resolve the algorithm Sleep step by step in the Ruby programming language
You may also check:How to resolve the algorithm Associative array/Iteration step by step in the ALGOL 68 programming language
You may also check:How to resolve the algorithm Rep-string step by step in the PureBasic programming language
You may also check:How to resolve the algorithm Count the coins step by step in the Forth programming language
You may also check:How to resolve the algorithm Sorting algorithms/Heapsort step by step in the Icon and Unicon programming language