#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    4
    Rep Power
    0

    Comparing Characters for a Game in C#


    I am making a hangman game to try and learn more of C#. I am getting an out of bounds error when comparing values. I am stuck and would like a wee nudge of help!

    Code:
    using System;
    using System.Collections.Generic;
    using System.Text;
    
    namespace files
    {
      class Program
      {
        static string[] wordList = new string[] { "beans", "cornbread", "clockwork" };
        static string word = string.Empty;
        static string letter = string.Empty;
    
        static void Main(string[] args)
        {
          Random rand = new Random();
          word = wordList[rand.Next(2)];
    
          Console.Write("Guess letter:  ");
          letter = Console.ReadLine();
          Guess(letter, word);
        }
    
        static void Guess(string letter, string word)
        {
          char[] checkLetter = letter.ToCharArray();
          char[] checkWord = word.ToCharArray();
          int j,k = 0;
    
          for (j = 0; j <= word.Length - 1; j++)
            for (k = 0; k <= word.Length - 1; k++)
              if (checkWord[j] == checkLetter[k])
                Console.Write("YES");
              else
                Console.Write("NO");
        }
      }
    }
  2. #2
  3. Forgotten Moderator
    Devshed Supreme Being (6500+ posts)

    Join Date
    Mar 2007
    Location
    Washington, USA
    Posts
    16,013
    Rep Power
    9616
    If you're using k to look at checkLetter then you need to bound it by checkLetter's length, not word's.
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2012
    Posts
    4
    Rep Power
    0
    Thank you!
  6. #4
  7. Contributing User
    Devshed God 1st Plane (5500 - 5999 posts)

    Join Date
    Aug 2011
    Posts
    5,792
    Rep Power
    508
    To build and run on linux I've named the program c.cs in current directory, then issue bash commands:
    $ mcs c.cs
    $ mono c.exe
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo