Here is my current code:
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Random random = new Random();
public int[] randomInt = new int[20];
public double[] randomDouble = new double[20];
public string searchKey;
public int intOrDouble; // 0 if int, 1 if double
public static int Search<T>(T[] inputArray, T key) where T : IComparable<T>
{
for (int i = 0; i < 20; i++)
{
if (inputArray[i].CompareTo(key) == 0)
{
return i;
}
}
return -1;
}
public Form1()
{
InitializeComponent();
}
private void randomIntGeneration_Click(object sender, EventArgs e)
{
randomNumbersTextBox.Clear(); // empty the textbox
intOrDouble = 0; // this is for knowing which parameter to send to search method
// generate 20 random integers and display them in the textbox
for (int i = 0; i < 20; ++i)
{
randomInt[i] = random.Next(0, 100);
randomNumbersTextBox.Text += randomInt[i].ToString() + " ";
}
}
private void randomDoubleGenerator_Click(object sender, EventArgs e)
{
randomNumbersTextBox.Clear(); // empty the textbox
intOrDouble = 1; // this is for knowing which parameter to send to search method
// generate 20 random doubles and display them in the textbox
for (int i = 0; i < 20; ++i)
{
randomDouble[i] = random.NextDouble() + random.Next(0, 100);
randomNumbersTextBox.Text += randomDouble[i].ToString() + " ";
}
}
private void searchArrayButton_Click(object sender, EventArgs e)
{
searchKey = searchKeyTextBox.Text;
if(intOrDouble == 0) // int array passed
{
resultsTextBox.Text = Search(randomInt, searchKey).ToString();
}
else
{
resultsTextBox.Text = Search(randomDouble, searchKey).ToString();
}
}
}
}
What i am trying to do is use this generic method. The GUI allows the user to generate a random array of either ints or doubles. I then want to use the Search method in the searchArrayButton_Click control to display whether or not the "searchKey" value entered is in the array. The error I am getting is "The type arguments for method 'Form1.Search(T[], T)' cannot be inferred from the usage. Try specifying the type arguments explicitly." They appear toward the bottom of the code when I try to call Search twice in the searchArrayButton_Click control.
You're trying to search an array of int or double values for a string. As a result, your call to Search has two arguments with two different types. That doesn't match the function signature.
You need to convert whatever is in that textbox into the value you are searching for, either an int or a double.
if(intOrDouble == 0) // int array passed
{
resultsTextBox.Text = Search(randomInt, int.Parse(searchKey)).ToString();
}
else
{
resultsTextBox.Text = Search(randomDouble, double.Parse(searchKey)).ToString();
}
Related
I have a basic form with a button and a textbox to insert a number
I want to keep the number inserted in the first index of the array, then if I put another number and I click the button, I want that number to be stored in the second index of the array and so on
I have to make a loop to increment the index but if I use the loop, the first number I put in the box, it's going to be stored in all the indexes of the array
Here's my code (doesn't work)
public partial class EXERCISES_ARRAYS : Form
{
int[] numbers = new int[5];
private void btnAdd_Click(object sender, EventArgs e)
{
int i = 0;
int insertedNumber = Convert.ToInt32(txtInsertedValue.Text);
for (int j = 0; j < 5; j++)
{
numbers[i] = insertedNumber;
i++;
if (i == 5)
{
btnAdd.Enabled = false;
}
}
}
}
You want a List, rather than an array. That will take care of all of this for you:
public partial class EXERCISES_ARRAYS : Form
{
List<int> numbers = new List<int>();
private void btnAdd_Click(object sender, EventArgs e)
{
numbers.Add(int.Parse(txtInsertedValue.Text));
}
}
I don't think you need to add a for loop for this. Try this
int[] numbers = new int[5];
int i = 0;
private void BtnAdd_Click(object sender, RoutedEventArgs e)
{
int insertedNumber = Convert.ToInt32(txtInsertedValue.Text);
numbers[i] = insertedNumber;
i++;
if (i == 5)
{
btnAdd.Enabled = false;
}
}
My instructions are: "Create a form that will display a running total of numbers a user enters." - to do this I've created a form with two text boxes (one for the number of values in the array and the other for the values in the array), a button to display it, and a label for it all to be displayed it. The issue is, is that my values aren't showing up - at all. My code is as below:
(** NOTE: I'm attempting to get the array to display in my label. txtInput is the inputted values and txtArrayValues is the number of elements.)
namespace Running_Total
{
public partial class frmEnter : Form
{
public frmEnter()
{
InitializeComponent();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int intNumber = Convert.ToInt32(txtArrayValues.Text);
string[] strArray;
strArray = new string[intNumber];
int i;
string j = "";
for (i = 0; i < intNumber; i++)
{
j = Convert.ToString(txtInput.Text);
strArray[i] += j;
}
lblDisplay.Text = strArray + " ";
}
}
}
Before, when I'd put lblDisplay.Text += j + " ";, it showed up in the label, but didn't pay any attention to the amount of elements the code was supposed to have. (Edit: this no longer works in my code.) (As is indicated in the title, I'm working with C# through Microsoft Visual Studio.)
It strongly depends on the fashion how the user inputs the numbers.
1) If he fills the textbox once with numbers and then presses the button to display them in the other box, it would suffice to use a string array catch the input and add it to the textbox or label that displays it. If he deletes the numbers in the input box and types new ones you could just repeat this step
namespace Running_Total
{
public partial class frmEnter : Form
{
// declare your Array here
string [] array = new string[1000];
int count = 0;
public frmEnter()
{
InitializeComponent();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
// save input
array[count] = inputTextBox.Text;
count++;
// display whole input
string output = "";
for(int i = 0;i < count; i++)
{
output += array[i];
}
// write it the texbox
outputTextBox.Text = output;
}
}
Does that answer your question or do you have another input pattern in mind?
Looking at your code, I realized that you want to display same number enteted in txtInput text repeatedly up to as many times as a number entered in a txtArrayValues.Text. So for example txtArrayValues. Text = "5" and txtInput.Text="2", your code will yield result "2,2,2,2,2". If that is what you want then the following code will achieve that.
using System.Linq;
namespace Running_Total
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
int len, num;
if (int.TryParse(txtArrayValues.Text, out len) &&
int.TryParse(txtInput.Text, out num))
{
lblDisplay.Text = string.Join(",", new string[len].Select(x => txtInput.Text));
}
}
}
}
Ok I'm trying to make a GUI dice game where the dice numbers are represented in textboxes.
I have to create a class that represents the dice and at least one of my methods has to correctly pass parameters by reference. My problem is that I am not too experienced with classes or passing parameters
I get an error at
rd.RollDice1(ref dice1);
rd.RollDice2(ref dice2);
(I am sure I have not constructed the RollDice class incorrectly)
Please is there anyone that can help me?
here is my code so far:
public partial class Form1 : Form
{
private RollDice rd;
public Form1()
{
InitializeComponent();
rd = new RollDice();
}
private void button1_Click(object sender, EventArgs e)
{
int dice1, dice2;
const int EYE = 1;
const int BOX = 6;
rd.RollDice1(ref dice1);
rd.RollDice2(ref dice2);
string result = string.Format("{0}", dice1);
string result2 = string.Format("(0)", dice2);
textBox1.Text = result;
textBox2.Text = result;
if (dice1 == EYE && dice2 == BOX)
{
MessageBox.Show("You rolled a Snake Eyes!");
}
if (dice1 == BOX && dice2 == BOX)
{
MessageBox.Show("You rolled BoxCars!");
}
else
{
MessageBox.Show("You rolled a {0} and a {1}", dice1, dice2);
}
}
}
}
class RollDice
{
const int EYE = 1;
const int BOX = 6;
public int RollDice1(ref int dieValue1)
{
Random randomNums = new Random();
dieValue1 = randomNums.Next(1, 7);
return dieValue1;
}
public int RollDice2(ref int dieValue2)
{
Random randomNums = new Random();
dieValue2 = randomNums.Next(1, 7);
return dieValue2;
}
}
}
Passing a variable with ref requires that variable to be initialized with a default value. If you don't set the two dices with an initial value your compiler complains about "Use of unassigned local variable xxxxx"
private void button1_Click(object sender, EventArgs e)
{
const int EYE = 1;
const int BOX = 6;
int dice1 = EYE;
int dice2 = BOX;
rd.RollDice1(ref dice1);
rd.RollDice2(ref dice2);
.....
However looking at your code there is no need to pass that values using ref, you could simply get the return value
dice1 = rd.RollDice1();
dice2 = rd.RollDice2();
of course you should change the two methods in your class to remove the parameter passed by ref
class RollDice
{
Random randomNums = new Random();
public int RollDice1()
{
return randomNums.Next(1, 7);
}
public int RollDice2()
{
return randomNums.Next(1, 7);
}
}
im pretty new to C# and i want to make a cardgame. What i have is a list of cards (strings) with names like c6, s3, h11, d13 where the character represents the colour and the number represents the value. When pressing a button the program takes a random string from the list and displays it in a textbox. From there the point of the game is to guess if the next random card will have a higher value or a lower value then the previous card.
What i want to do is to take the string from the textbox and turn it into a int so that i can compare the value of the previous card with the new one. Only problem is how do i get rid of the c in c6 so i can convert it by using parse.
This is my code.
public partial class MainWindow : Window
{
static Random rndmlist = new Random();
Random rndm = new Random();
List<string> deck = new List<string>();
int score = 0;
public MainWindow()
{
InitializeComponent();
}
private void test_Click(object sender, RoutedEventArgs e)
{
//disregard this
foreach (string j in deck)
{
testbox.Text += j + ", ";
}
}
private void btnstart_Click(object sender, RoutedEventArgs e)
{
//this is where i add all the cards to the list
for (int i = 1; i <= 13;)
{
deck.Add("c" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("s" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("h" + i);
i++;
}
for (int i = 1; i <= 13; )
{
deck.Add("d" + i);
i++;
}
}
private void btnbegin_Click(object sender, RoutedEventArgs e)
{
//this is where i take a random card from the list and display it in textBox2
int r = rndmlist.Next(deck.Count);
textBox2.Text = ((string)deck[r]);
//disregard this
testbox.Text += ((string)deck[r]) + ", ";
deck.Remove((string)deck[r]);
}
private void btnhigh_Click(object sender, RoutedEventArgs e)
{
//this is where i want to compare the cards.
}
}
Thank you in advance for reading this. (:
I'd better create a class Card, which represents a card, with 2 properties: Color and Number and implemented method Card.ParseFromString()
Try this,
string SubString = MyString.Substring(1);
But take care if the string is empty, it is an error case.
Assuming there will always be one (and only one) character before the number, you can simply do this:
string numberAsString = "c2".Substring(1);
And to make that an int:
int number = Int32.Parse(numberAsString);
You can use Regex to replace all alpha characters eg
string result = Regex.Replace(myString, #"[a-zA-Z\s]+", string.Empty);
string str = "c12";
var noChars = str.SubString(1); // take a new string from index 1
var number = Int32.Parse(noChars);
I'm trying to declare the array Scores as an array of textboxes. It doesn't have a size. I also need to declare it as an instance variable, and instantiate it in the method, CreateTextBoxes. I keep getting an error, "Scores is a field but is used like a type."
namespace AverageCalculator
{
public partial class AverageCalculator : Form
{
private TextBox[] Scores;
public AverageCalculator()
{
InitializeComponent();
}
private void AverageCalculator_Load(object sender, EventArgs e)
{
btnCalculate.Visible = false;
}
private void btnOK_Click(object sender, EventArgs e)
{
int intNumTextBoxes;
intNumTextBoxes = Convert.ToInt32(txtNumScores.Text);
this.Height = 500;
btnCalculate.Visible = true;
btnOK.Enabled = false;
}
private void CreateTextBoxes(int number)
{
Scores[number] = new Scores[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
}
}
your CreateTextBoxes should probably be something like this:
private void CreateTextBoxes(int number)
{
Scores = new TextBox[number];
for (int i = 0; i < number; i++)
{
Scores[i] = new TextBox();
}
}
As Adil suggested, a List<TextBox> is probably better in this case.
You need to instantiate TextBox but number should be constant You can read more about the array creation expression here. Its better to use List instead of array if you want variable size.
Scores = new TextBox[number];
Using List
List<TextBox> Scores= new List<TextBox>();
Your code should read:
Scores = new TextBox[number];
// do things with this array
The problem is in
private void CreateTextBoxes(int number)
{
Scores[number] = new Scores[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
When you are trying to initialize the array, you are using the name of the field as they type and are including an index to the field name. Just change the new type to TextBox and remove the index accessor like this:
private void CreateTextBoxes(int number)
{
Scores = new TextBox[number];
int intTop = 150;
for (int i = 0; i < 150; i++)
{
}
}
replace line 1 with line 2
Scores[number] = new Scores[number];
Scores[number] = new TextBox();
You can't do this.
Scores[number] = new Scores[number];
Use a list of TextBox.