I am trying to create a word search game. the problem is I am unable to insert words into a TableLayoutPanel. When I wrote this, I got a compile error that says "no overload for method 'placewords' takes '5' arguments.
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
Random r = new Random();
for (int a = 0; a < tableLayoutPanel1.ColumnCount; a++)
{
for (int b = 0; b < tableLayoutPanel1.RowCount; b++)
{
Label nl = new Label();
int x = r.Next(65, 90);
char c = (char)x;
nl.Text = c.ToString();
tableLayoutPanel1.Controls.Add(nl, a, b);
}
}
}
private void newGameToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Restart();
}
private void PlaceWords()
{
string[] words = { "byte", "char" };
Random rn = new Random();
foreach (string p in words)
{
String s = p.Trim();
bool placed = false;// continue trying to place the word in // the matrix until it fits
while (placed == false)// generate a new random row and column
{
int nRow = rn.Next(30);// generate a new random x & y direction vector
int nCol = rn.Next(30);// x direction: -1, 0, or 1
int nDirX = 0; // y direction -1, 0, or 1
int nDirY = 0; // (although direction can never be 0, 0, this is null)
while (nDirX == 0 && nDirY == 0)
{
nDirX = rn.Next(3) - 1;
nDirY = rn.Next(3) - 1;
}
placed =PlaceWords(s.ToUpper(),nRow,nCol,nDirX,nDirY);
}
}
}
Your PlaceWords method doesn't accept that many parameters, in fact, it accepts no parameters.
Further more, the way it looks, your PlaceWords is a recursive function that won't exit, leading to a stack overflow.
To fix this, you need to create a second PlaceWords function that accepts all 5 parameters, and does whatever PlaceWords does, and returns a boolean.
It looks like your nested for loops in Form1_Load should be placing random characters into tableLayoutPanel1. You then need to call PlaceWords() which will determine the location and direction to place each word in the words list. Near the end of PlaceWords you are calling PlaceWords(s.ToUpper(),nRow,nCol,nDirX,nDirY) which is supposed to actually put the word into tableLayoutPanel1. This second PlaceWords with 5 parameters should have a different name (I suggest PlaceString); it should not be trying to call the same Placewords method that it is in.
You need to then write the method PlaceString that will look like:
public bool PlaceString(string s, int nRow, int nCol, int nDirX, int nDirY)
{
/* whatever code you need to put the string into tableLayoutPanel1 */
}
Related
It's a favorite panel.
You can select numbers (with button click) and than I would like to add this number to an array and than get a random number from this array.
public int runs;
public int randomNumber;
public int[] favorites = new int[75];
public void RandomButton()
{
if (DataController.Instance.group == 3)
{
favorites[randomNumber] = UnityEngine.Random.Range(0, favorites.Length);
Debug.Log(favorites[randomNumber]);
}
}
public void b0()
{
for (runs = 0; runs < favorites.Length; runs++)
{
favorites[runs] = 0;
}
}
public void b1()
{
for (runs = 0; runs < favorites.Length; runs++)
{
favorites[runs] = 1;
}
}
I'm stuck , because I get random number between 0 - 75. I would like to have a random number from the "favorites" array after I click on the buttons.
What you are doing here
favorites[randomNumber] = UnityEngine.Random.Range(0, favorites.Length);
Is assign a random value between 0 and 74 to an item in your array .. depending on whatever value randomNumber has at that moment ...
What you rather want to do is actually access the value from the array using the random value as index like
randomNumber = favorites [UnityEngine.Random.Range(0, favorites.Length)];
Debug.Log(randomNumber);
However what difference will it make if you are filling your array with always the same numbers using b0 and b1?
After running these methods all elements are either 0 or 1 anyway ...
Anyway in your question you are also asking for how to Add a number.
You shouldn't use an array for this but rather a List<int> like
public List<int> favorites = new List<int>();
public void AddNumber(int newNumber)
{
favorites.Add(newNumber);
}
public void RandomButton()
{
if (DataController.Instance.group == 3)
{
randomNumber = favorites[UnityEngine.Random.Range(0, favorites.Count)];
Debug.Log(randomNumber);
}
}
if (DataController.Instance.group == 3)
{
var randomIndex = UnityEngine.Random.Range(0, favorites.Length);
Console.WriteLine(favorites[randomIndex]); // random item from your array
}
answer
I have a program that has two text boxes for input. They are variableOne and VariableTwo. I can't figure out the expression that i need to put in the for loop to show these numbers and the numbers in between them. For example if i put a 1 and 11 i need 2-10 in between those. This is what i have so far.. I know i don't have the else expressions yet either.
namespace loops
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void whileButton_Click(object sender, EventArgs e)
{
double variableOne = 0;
double variableTwo = 0;
int i = 0;
if (double.TryParse(variableOneText.Text, out variableOne))
{
if(double.TryParse(variableTwoText.Text, out variableTwo))
{
while(i<= (variableOne) && (variableTwo))
{
i++;
}
outputLabel.Text = i.ToString();
}
}
}
}
}
It's still not clear what you want to achieve.
I make a guess here:
INPUT: two rational numbers.
OUTPUT: all natural numbers in between.
e.g. IN 8.1, 14.9 -> OUT 9, 10, 11, 12, 13
here's the code
StringBuilder output = new StringBuilder();
double variableOne = 8.1;
double variableTwo = 14.9;
double start = 0;
double end = 0;
bool isShowingInitialVariable = true;
//if (double.TryParse(variableOneText.Text, out variableOne))
//{
// if (double.TryParse(variableTwoText.Text, out variableTwo))
// {
//take allways the smaller number to start and the greater for end
start = Math.Min(variableOne, variableTwo);
end = Math.Max(variableOne, variableTwo);
//build your output
output.AppendLine(string.Format("first variable {0}, second variable {1}", variableOne, variableTwo));
output.AppendLine(string.Format("min", start));
output.AppendLine(string.Format("max", end));
output.AppendLine(string.Format("difference {0}", end - start));
//all the natural numbers in between.
for (int i = (int)Math.Ceiling(start); i < Math.Floor(end); i++)
{
output.AppendLine(i.ToString());
}
Console.WriteLine(output.ToString());
// outputLabel.Text = output.ToString();
// }
//}
This is my random unique numbers generator I try to create for my cards software. It generates numbers and write into array OK. I have problem with the loop here. when integer i reaches 29, it stops growing and code cycles infinitely and never reaches 30, which would stop the loop.
Without the if statement it works, but it won't fill the range needed.
fixed the code, now works OK, the initial value in array was the problem. now I ged needed 0-29 values
public partial class Form1 : Form
{
int[] rndCards = new int[30];
public Form1()
{
InitializeComponent();
richTextBox1.Text = #"random numbers";
}
private void button1_Click(object sender, EventArgs e)
{
int i = 0;
rndCards = new int[30];
richTextBox1.Clear();
Random rnd = new Random();
while (i < 30)
{
int cardTest = rnd.Next(0, 30);
while (rndCards.Contains(cardTest))
{
cardTest++;
if (cardTest == 31)
{
cardTest = 1;
}
}
rndCards[i] = cardTest;
i++;
}
i = 0;
while (i < 30)
{
rndCards[i] = rndCards[i] -1;
richTextBox1.Text += rndCards[i] + ", ";
i++;
}
}
}
You problem lies in the simple fact that the array already contains the number 0 when you create it (because each item of an array is initialized to the default value for its member's type) That's why you should start your i from 1 and not zero.
int i = 1;
Alternative Simpler Approach:
You can do this as a simple random number generation:
Random rnd = new Random();
rndCards = Enumerable.Range(0, 30).OrderBy(x => rnd.Next()).ToArray();
foreach(var card in rndCards)
{
// do something
}
rnd.Next(0,30) would return a random number from 0-29.
From the documentation for Random.Next(Int32, Int32):
The Next(Int32, Int32) overload returns random integers that range from minValue to maxValue – 1. However, if maxValue equals minValue, the method returns minValue.
Use int cardText = rnd.Next(0, 31);, and this should solve your issue.
The upper bound is exclusive (C# Random.Next - never returns the upper bound?).
int cardTest = rnd.Next(0, 31);
i need to put the contents of an text box that is a string into an array.
i have seen lots of people asking how to put each letter as an index in the array but i want the whole string in one index.
for context
i am making an application for a hotel booking for an assignment, it takes a name, room number and length of stay. it also stores room size with radio buttons. then there is another button and a textbox that when you type a room size (Single, double or triple) it will display how many people have book that room type and the name on the booking.
any help would be greatly appreciated. here is what i have done and i picture of what the application is meant to look like.
namespace Assignment2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
// MessageBox.Show("Initalize");
}
string[] CusName = new string[150];
int[] RNumber = new int[150];
int[] nights = new int[150];
string[] RSize = new string[150];
string name;
bool blnnumcheck;
bool blnNightsCheck;
private void Form1_Load(object sender, EventArgs e)
{
// MessageBox.Show("Load");
}
private void TxtName_TextChanged(object sender, EventArgs e)
{
name = TxtName.Text;
}
private void btnConfirm_Click(object sender, EventArgs e)
{
string size;
int Roomnum, night;
blnNightsCheck = int.TryParse(txtLengthofStay.Text, out night);
if (!System.Text.RegularExpressions.Regex.IsMatch(TxtName.Text, "([a-zA-Z])"))
{
MessageBox.Show("Invalid Name Please try again");
}
blnnumcheck = int.TryParse(txtRoomNumber.Text, out Roomnum);
if (!blnnumcheck )
{
MessageBox.Show("Invalid Room Number Please try again" );
}
if (Roomnum >= 150)
{
MessageBox.Show("Invalid Room Number Please try again");
}
}
}
}
this what the completed one is supposed to look like
try this:
List<string> myArray = new List<string>();
myArray.Add(myTextBox.Text);
string data = "Hello, Good Morning";
string[] stringArray = new string[]{ data };
Console.WriteLine(stringArray[0]);
If you know how to create arrays, continue reading, if you don't, jump to the content below the horizontal line.
You create an int array using int[], right? So if you want to create a string array, use string[]!
Here is more code:
string[] myArray = new string[10];
//add stuff into the array
myArray[0] = "Hello";
myArray[1] = "World";
//etc
That is simple enough, right? You can do all the things you can do with an int array to a string array.
If you don't know how to create an array, start to read here
You declare an array like this:
type[] array_name = new type[length];
And you can put stuff in the array like this:
array_name[index] = some_stuff;
Thus, you can create an array of strings like this:
string[] myArray = new string[10];
//add stuff into the array
myArray[0] = "Hello";
myArray[1] = "World";
//etc
Just remember, whatever type you want an array to be, write whatever type followed by [] and give it a name!
You can loop through a 2D array like this:
for (int i = 0 ; i < maxX ; i++) { // maxX is the maximum index of the array in the first dimension
for (int j = 0 ; j < maxY ; j++) {
//you can access the array here with array[i][j]
}
}
I have been playing around and wrote this little piece of code. I am trying to flip a coin defined number of times and then count how many tails and heads I am getting. So here it is:
private void Start_Click(object sender, EventArgs e)
{
int headss = 0;
int tailss = 0;
int random2, g;
string i = textBox1.Text;
int input2, input;
bool NumberCheck = int.TryParse(i, out input2);
if (textBox1.Text == String.Empty) // check for empty string, when true
MessageBox.Show("Enter a valid number between 0 and 100000.");
else // check for empty string, when false
if (!NumberCheck) // number check, when false
{
textBox1.Text = String.Empty;
MessageBox.Show("Enter a valid number between 0 and 100000.");
}
else
{
input = Convert.ToInt32(textBox1.Text);
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
if (random2 == 0)
{
headss++;
}
else if (random2 == 1)
{
tailss++;
}
}
}
heads.Text = Convert.ToString(headss);
tails.Text = Convert.ToString(tailss);
}
The problem is that I keep getting problems while displaying the content. It's not even close to display they right result. Any ideas?
EDIT. Solution: move following line 3 lines up :D
Random random = new Random();
Instead of
for (g = 0; g < input; g++)
{
Random random = new Random();
random2 = random.Next(2);
}
Declare a single Random for use throughout:
private Random randomGenerator = new Random();
private void Start_Click(object sender, EventArgs e)
{
// ...
for (g = 0; g < input; g++)
{
random2 = randomGenerator.Next(2);
}
// ...
}
You should use only one Random object to generate good (as good as default Random does) random sequence.
The default constructor for random take the systmem time as seed. Therefore, if you generate lots of them in a short amount of time they will all generate the same sequence of random numbers. Pull the random object out of the loop and this effect will not occur.
With RandomGenerator. This code will count how many times coin has been flipped. It will end with 3 consecutive HEADS.
private RandomGenerator rgen = new RandomGenerator ();
public void run () {
int value = 0;
int total = 0;
while (value != 3) {
String coinFlip = rgen.nextBoolean() ? "HEADS" : "TAILS";
println (coinFlip);
if (coinFlip == "HEADS") {
value+=1;
} else {
value=0;
}
total +=1;
}
println ("It took "+total+" flips to get 3 consecutive heads");
}