I think I found what the problem is. And I think my code fails when i try to replace a value in an array with another value from another array. I uses a for loop and then find out "i", the index and I try to replace one value in one array. There is some mixup in the indexes, but I can't figure it out!
What's below is as far as I have come.
There are some Norwegian words in there but don't let them confuse you. And I should tell you that I try to make a hangman game.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _Default : System.Web.UI.Page
{
char [] arrayOrd;
char[] bokstav;
char[] byggeOrd;
protected void Page_Load(object sender, EventArgs e)
{
//Session for remembering what word is gonna be guessed
if (Session["arrayOrd"] != null)
{
arrayOrd = (char[])Session["arrayOrd"];
}
//This session contains the underscores
if (Session["byggeOrd"] != null) {
byggeOrd = (char[])Session["byggeOrd"];
}
}
protected void Page_Unload(object sender, EventArgs e)
{
Session["arrayOrd"] = arrayOrd;
Session["byggeOrd"] = byggeOrd;
}
protected void btnStart_Click(object sender, EventArgs e)
{
string ord = txtOrd.Text.ToLower();
arrayOrd = ord.ToCharArray();//Puts text from a textbox to an array called arrayOrd
List<char> list = new List<char>();
for (int i = 0; i < arrayOrd.Length; i++) {//Put underscores for as long arrayOrd is in a list.
labRiktigBokstav.Text += "_ ";
list.Add('_');
}
byggeOrd = list.ToArray(); //Put's the list that contains underscores in an array
}
//Checking if a letter is in the word
protected void btnSjekkOrd_Click(object sender, EventArgs e)
{
string BSjekk = txtBokstavSjekk.Text.ToLower();
bokstav = BSjekk.ToCharArray();
if (arrayOrd.Contains(bokstav[0]))
{
for (int i = 0; i < arrayOrd.Length; i++)
{
if (arrayOrd[i] == bokstav[0])
{
byggeOrd[Array.IndexOf(byggeOrd, byggeOrd[i])] = arrayOrd[i]; //I think there is something wrong here!!!!!
string resultat = new string(byggeOrd);
labRiktigBokstav.Text = resultat;
}
}
}
else
{
//Print out that the guessed letter is wrong
}
}
}
The following line is wrong:
byggeOrd[Array.IndexOf(byggeOrd, byggeOrd[i])]
You are getting the index of a value through its very index.
int ind = Array.IndexOf(byggeOrd, byggeOrd[i]);
The code above can retrieve any index. That's why it can modify an unintended value. You should replace it with
if (arrayOrd[i] == bokstav[0]){
byggeOrd[i]= arrayOrd[i];
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.