Reputation: 17
Hi stack overflow users,
I have created a fully functional Hangman Game in C# now I am polishing the last parts before handing the assignment in.
I decided to create three different difficulties "Easy" "Medium" "Hard" instead of letting the user pick the amount of life.
Now to the question?
Is there a function to add words into the word list (which then get randomly selected by a method)? I would like to limit the min and max length of the words that the user adds onto the list of words.
Below is the class for my WordList.
using System;
using System.Collections.Generic;
class WordList
{
public static list <string>word = new list<string>();
public void Showwordlist()
{
word.sort();
foreach (string word in words)
{
console.WriteLine("- " + word);
}
}
public void Addwords(string input)
{
word.add(input);
}
}
Upvotes: 0
Views: 188
Reputation: 9789
Add a check to see if it meets the minimum length and is less than the maximum length:
private int minimumLength = 4;
private int maximumLength = 20;
public void Addwords(string input)
{
if(input.Length >= minimumLength && input.Length <= maximumLength)
word.add(input);
else
MessageBox.Show("Word length must be between " + minimumLength +
@" and " maximumLength + " characters");
}
I'm assuming that the bounds are all inclusive so I'm using the >=
and <=
operators. The MessageBox.Show
is assuming that you're using Windows Forms. Otherwise, handle the error message appropriately.
Upvotes: 4
Reputation: 7176
You can also use RegularExpressions to limit the characters used in the words as well as the length. In the regular expression below, only words that contain upper and lower case letters that are between 2 and 10 characters would be allowed.
public void Addwords(string input)
{
Match match = Regex.Match(input, "^[a-zA-Z.]{2,10}$");
if (match.Success)
{
word.add(input);
}
}
Upvotes: 0
Reputation: 152654
Like this?
public void Addwords(string input)
{
if(input.Length < minLength)
throw new Exception("Too Short"); // example only - throw a better exception
if(input.Length > maxLength)
throw new Exception("Too Long"); // example only - throw a better exception
word.add(input);
}
Upvotes: 0