-
Re: Please don't cringe
Code:
namespace keyPad
{
class Program
{
Dictionary<string, int> numberMap;
//Rest of the program
}
}
To access numberMap from all static methods (without having to pass it around), declare it as a class variable by putting the declaration (above, bold/underlined) right after the class Program statement.
Some info on variable scope: http://www.csharpuniversity.com/2009...f-c-variables/
Also, don't forget to make sure you have the using directive: using System.Collections.Generic at the top of your source file.
Finally, check your declarations for W, X and Y... looks like you said 2 when you probably meant 9.
Hope that helps!
-
Re: Please don't cringe
Okay, so I changed the X,Y,Z numbers. I made sure numberMap was declared at the class level, but there seems to be something wrong with the bool phase. When ever I enter a number 1-9, it displays the "Hey! That number wasn't valid!" text. I coudn't locate the problem.
-
Re: Please don't cringe
Ah, okay so my example was slightly misleading. When it prompts, it should be prompting you to enter a letter (not a number) since your program accepts a letter and outputs a number. Thus, displaying the error message when you enter a number is the correct behavior.
Here is the full text of a program that works
Code:
using System;
using System.Collections.Generic;
namespace tmpCG20111206
{
class Program
{
static Dictionary<string, int> numberMap = new Dictionary<string, int>()
{
{ "a", 2 }, { "b", 2 },{ "c", 2 },
{ "d", 3 },{ "e", 3 },{ "f", 3 },
{ "g", 4 },{ "h", 4 },{ "i", 4 },
{ "j", 5 },{ "k", 5 },{ "l", 5 },
{ "m", 6 },{ "n", 6 },{ "o", 6 },
{ "p", 7 },{ "q", 7 },{ "r", 7 },
{ "s", 7 },{ "t", 8 },{ "u", 8 },
{ "v", 8 },{ "w", 9 },{ "x", 9 },
{ "y", 9 },{ "z", 9 }};
public static void Main(string[] args)
{
Console.WriteLine(requestInputAndConvertToNumber());
Console.WriteLine("Program complete");
Console.ReadLine();
}
public static int requestInputAndConvertToNumber()
{
string input = null;
while (true)
{
//Prompt user
Console.Write("Enter letter: ");
//Get input from the user
input = Console.ReadLine(); //Also ReadKey might be useful
//Check to see if this input is in the dictionary; if so store the numerical value
// in result
int result = 0;
bool inDictionary = numberMap.TryGetValue(input, out result);
if (!inDictionary)
{
//Complain
Console.WriteLine("Hey! That letter wasn't valid!");
continue; //Restart the loop to try again
}
//Otherwise return the result (the corresponding integer)
return result;
}
}
}
}
-
Re: Please don't cringe
Thanks to everyone for the help!