0
//capture input value for peak size and return 
public static int GetPeakSize()
{
    //declare variables, intitialize and parse after input
    int peak;
    Console.WriteLine("\nPlease enter the peak size (must be a number 1-10): ");
    peak = int.Parse(Console.ReadLine());

    //if user enter anything that is not inside the 1-10 range, default
    //to 3
    if (peak < 1 || peak > 10)
    {
        peak = 3;
    }

    return peak;
}

In the method above I'm just trying to gather input, parse it, and if the input does not fall in the range of 1-10, return a default value of 3. But instead of just validating numerical input, I want to return a default value of 3 if ANYTHING but the numerical values of 1-10 are entered. So if they enter "four" instead of 4, I'd like the value to default to 3. I wish I could do something along the lines of if (value != int || value < 1 || value > 10)......default = 3. I know this can't be done but is there anyway around it?

dee-see
  • 23,668
  • 5
  • 58
  • 91
  • Why not just disallow non-numerical input? If they enter "four" display a message that says "Please enter numbers only." Seems confusing for the user to enter "four" and just have the program silently assume 3. – eddie_cat Sep 15 '14 at 20:13
  • @eddie_cat Yeah I know, it's assignment requirements though. –  Sep 15 '14 at 20:36
  • gotcha, just figured it was worth noting. – eddie_cat Sep 15 '14 at 20:36

2 Answers2

2

You might want to use TryParse instead:

    int peak;
    Console.WriteLine("\nPlease enter the peak size (must be a number 1-10): ");
    if (!int.TryParse(Console.ReadLine(), out peak) || peak < 1 || peak > 10)
    {
        peak = 3;
    }

The code above will attempt to parse the input into an int -- if it could not, or if the parsed value falls outside of your range constraints, it overrides peak to 3 before continuing on.

EDIT: Missed the range constraints.

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
2

Use int.TryParse. int.Parse will throw if the input is non-numeric.

int peak = 0;
bool parseSuccess = int.TryParse(input, out peak);

if (!parseSuccess || peak < 1 || peak > 10)
{

}

int.TryParse will return false if the input is not valid, and if it is valid, then the parsed value will be contained in the "out" parameter (peak in this case).

BradleyDotNET
  • 60,462
  • 10
  • 96
  • 117
  • I like this as an alternative to Cory's answer. Will use either one. Thank you. –  Sep 15 '14 at 20:38