Help with KeyboardUtility class

WB1975

Well-known member
Joined
Apr 3, 2020
Messages
87
Programming Experience
Beginner
I thought it might be a good idea to have a class that handles all the keyboard stuff so i dont have to keep writing input code over and over i mean thats one of the pros i read about OOP, reusable code.

I have created a Class called KeyboardUtility and I have it returning number only input when the function is called.

I'm just wondering if im on the right track as usual, or whether this should be done another way.

I only have one function, but want to add like 1 to 4 menu, or y / n question or letters only etc etc

any ideas/advice would be accepted with arms wide open!!!

C#:
using System;
using System.Collections.Generic;
using System.Text;

namespace FootballLeague
{
    class KeyboardUtility
    {

        public static int NumberOnlyInput(string askForNumbers)
        {
            bool finishedEnteringNumbers = false;
            string userInput;
            int userNumberReturned;

            while (!finishedEnteringNumbers)
            {
                Console.WriteLine(askForNumbers);
                userInput = Console.ReadLine();
                bool isNumeric = int.TryParse(userInput, out userNumberReturned);
                if (isNumeric)
                {
                    return userNumberReturned;
                }
                else
                    {
                        Console.WriteLine("That is not a valid number...");
                    }
            }
            return 0;
        }
    }
}
 
I can simply call the function in other code like this:

C#:
int beerCount = KeyboardUtility.NumberOnlyInput("Please enter the number of beers you want:");
 
I would probably write that like this:
C#:
public static class KeyboardUtility
{
    public static int GetInt32(string prompt)
    {
        Console.WriteLine(prompt);

        var isValid = int.TryParse(Console.ReadLine(), out var number);

        while (!isValid)
        {
            Console.WriteLine("Please enter a valid number.");
            Console.WriteLine(prompt);

            isValid = int.TryParse(Console.ReadLine(), out number);
        }

        return number;
    }
}
 
Another quick silly question,

Are floats used for general decimal or double?
float is to double as short is to int. Basically, use double and int for floating-point and integer numbers unless you have a specific need to use something else. That means that you should almost never use float and short because, even if you don't need the increased range of double and int, they are more efficient for the processor to deal with. Use decimal instead of double if you need the extra precision, e.g. for financial calculations where rounding errors could accumulate and make a significant difference, and use long instead of int if you need the extra range. That should be it for the vast majority of your numeric needs.

That's rather off-topic for this thread though, so let's not get any further afield from the original topic of the thread.
 
Yes , you answered my question perfectly thanks.

on topic... "Will it be used for output as well? "
i'm really sorry, I dont understand the question, do you just mean will there be methods printing results etc?
 
ConsoleInput would be OK for a class intended exclusively to gather input from the console. If it's being used for output as well then the name is inappropriate. I wouldn't necessarily consider prompts and the like as being output. They are technically but their purpose is to elicit input. If a method's main purpose was to output data to the user though, the name would be inappropriate.
 
And a do-while version of post #3:
C#:
public static class ConsoleInputHelper
{
    public static int GetInt32(string prompt)
    {
        do
        {
            Console.WriteLine(prompt);
            if (int.TryParse(Console.ReadLine(), out var number))
                return number;

            Console.WriteLine("Please enter a valid number.");
        } while (true);
    }
}
 
here is my double method

C#:
public static double GetDouble (string prompt)
        {
            Console.WriteLine(prompt);

            var isValid = double.TryParse(Console.ReadLine(), out var number);

            while (!isValid)
            {
                Console.WriteLine("Please enter a valid number.");
                Console.WriteLine(prompt);

                isValid = double.TryParse(Console.ReadLine(), out number);
            }

            return number;
        }

and my yes no method, which im sure there is a better way of writing, im not happy with the false returning on line 31
what is the best way to handle this?

C#:
public static bool GetYesNo (string prompt)
        {
            Console.WriteLine(prompt);
            bool isValid = false;

            while (!isValid)
            {
                Console.WriteLine("Please enter (y/Y or n/N)");
                Console.WriteLine(prompt);

                string userChoice = Console.ReadLine();
                char firstChar = userChoice[0];
                char firstCharUpper = char.ToUpper(firstChar);
                switch (firstCharUpper)
                {
                    case 'Y':
                        return true;
                        isValid = true;
                        break;

                    case 'N':
                        return false;
                        isValid = true;
                        break;

                    default:
                        Console.WriteLine("Not valid");
                        break;
                }
            }
            return false;
        }
 
Give this a spin:
C#:
static bool GetYesNo(string prompt)
{
    Console.Write($"{prompt} [Y/N]: ");
    while (true)
    {
        char ch = Console.ReadKey(true).KeyChar;
        switch (char.ToUpper(ch))
        {
            case 'Y':
            case 'N':
                Console.WriteLine(ch);
                return ch == 'Y';
        }
        SystemSounds.Beep.Play();
    }
}
 
Back
Top Bottom