-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUserGet.cs
More file actions
89 lines (84 loc) · 2.43 KB
/
UserGet.cs
File metadata and controls
89 lines (84 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
namespace InputHandler;
static class UserGet
{
/// <summary>
/// Prompts user for an int, and tries to parse it until user
/// supplies valid value
/// </summary>
/// <param name="prompt">Prompt message to display</param>
/// <returns>Valid integer</returns>
public static int GetInt(string prompt)
{
while (true)
{
Prompt(prompt);
int output;
if (int.TryParse(Console.ReadLine(), out output))
{
return output;
}
Console.WriteLine("skriv en int.");
}
}
/// <summary>
/// Prompts user for a char, checks that the input is a digit or letter
/// before returning it.
/// </summary>
/// <param name="prompt">Prompt message to display</param>
/// <returns>Digit or letter char</returns>
public static char GetChar(string prompt)
{
Prompt(prompt);
char output;
do
{
output = char.ToUpper(Console.ReadKey(true).KeyChar);
}
while (!char.IsLetterOrDigit(output));
return output;
}
/// <summary>
/// Prompts the user for a char, that must be one of the chars
/// supplied. Will ask until valid choice is made.
/// </summary>
/// <param name="prompt"></param>
/// <param name="acceptedChars">Prompt message to display</param>
/// <returns>Char of the supplied set</returns>
public static char GetCharOfSet(string prompt, char[] acceptedChars)
{
while (true)
{
char output;
output = GetChar(prompt);
Console.Write(output + "\n");
if (Contains(output, acceptedChars))
return output;
else
Console.WriteLine("Felaktig input");
}
}
public static bool Contains(char c, char[] chars)
{
for (int i = 0; i < chars.Length; i++)
{
if (c == chars[i])
{
return true;
}
}
return false;
}
/// <summary>
/// Prompts the user for a string
/// </summary>
/// <param name="prompt">Prompt message to display</param>
/// <returns>A string</returns>
public static string GetString(string prompt)
{
Prompt(prompt);
return Console.ReadLine();
}
//The format of the prompt
private static void Prompt(string prompt) =>
Console.Write($"{prompt}: ");
}