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);
Related
Hello guys I am new to coding, and new to arrays as well and I was wondering how can I make this code to stop when there is no more names in the array, and from stop saying the number 10 always before the names. As well to show the position of the names one number above, not just starting from 0, but from 1.
Here is what I have so far.
string[] list = new string[10];
int pos = 0;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string StudentName;
StudentName = textBox1.Text;
list[pos] = StudentName;
pos++;
textBox1.Text = "";
}
private void button2_Click(object sender, EventArgs e)
{
MessageBox.Show(list.GetLength(0).ToString());
string message;
for (int i = 0; i < lista.GetLength(0); i++)
{
message = "";
message = "The student" + " " + list[i] + " has the position " + i ;
MessageBox.Show(message);
}
}
Use a dynamic array, aka List<T>
List<string> list = new List<string>();
Instead of manually keeping track of the position, just add the item to the end:
list.Add(StudentName);
You can check the number of current items in the list by using .Count.
for (int i = 0; i < list.Count; i++) {...}
But you can also use a foreach loop to iterate over all the items in the list, but this way you do not get the position automatically.
foreach(var item in list){...}
For the sake of completeness, another way would be to filter out empty entries.
Linq is especially great for working with Enumerables like these:
https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.where?view=net-6.0
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string[] list = new string[10];
list[0] = "test1";
list[1] = "test2";
for (var index = 0; index < list.Length; index++)
{
var s = list[index];
Console.WriteLine($"[{index}] {s}");
}
// Filter out null, an empty string or only whitespace characters from the array
list = list
.Where(c => !string.IsNullOrWhiteSpace(c))
.ToArray();
Console.WriteLine("==========================");
for (var index = 0; index < list.Length; index++)
{
var s = list[index];
Console.WriteLine($"[{index}] {s}");
}
}
}
https://dotnetfiddle.net/g7e0Nm
First you can specify the maximum capacity of your array using a const
const int arrayCapacity = 10;
string[] list = new string[arrayCapacity];
int pos = 0;
Then you should add some validation if the array is full, according to your maximum capacity, and/or if the textbox is empty.
private void button1_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Textbox was empty");
return;
}
if (pos > arrayCapacity - 1)
{
MessageBox.Show("Array is full");
textBox1.Clear();
return;
}
list[pos] = textBox1.Text;
pos++;
textBox1.Clear();
}
And the last step is to create a new array in any case you have a smaller number of students than your initial array's capacity
private void button2_Click(object sender, EventArgs e)
{
var arr = list.Where(x => !string.IsNullOrEmpty(x)).ToArray();
for (int i = 0; i < arr.Length; i++)
{
string message = "The student" + " " + arr[i] + " has the position " + (i + 1);
MessageBox.Show(message);
}
}
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();
}
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));
}
}
}
}
I'm making a calculator in GUI, and I need some help.
When I enter some data in a text box, I need to store it in an array. This is how I thought of it.
int numOfPackages;//used to get user input
private void button3_Click(object sender, EventArgs e)
{
int[] weight = new int[numOfPackages];
for(int i = 0; i < numOfPackages; i++)
{
weight[i] = Convert.ToInt32(weightBox.Text);
}
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
}
And when I try to display the elements, it gives me the indexOutOfRange exception.
So, how do I display the elements of that array?
Thanks in advance.
This line
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
should be
foreach (int w in weight)
totalCostLabel.Text = "" + w;
Your current code iterates the array of weights, and tries to use the weight as an index into the array of weights, causing an index out of range exception.
Another problem is with the first loop: you are setting all values of weight to the same number:
weight[i] = Convert.ToInt32(weightBox.Text); // That's the same for all i-s
If weights are to be different, they should come from different weight boxes, or the string from a single weightBox should be processed in such a way as to produce multiple numbers (for example, by using string.Split).
You have multiple problems here. First is this:
foreach (int i in weight)
totalCostLabel.Text = "" + weight[i];
This is iterating the weight array and using each value in that array. You then use that value as an index. Take the following example:
weight[0] = 0
weight[1] = 1
weight[2] = 15
In your code, the first two entries will work because there is an index of 0 and an index of 1. But when it gets to the last entry, it looks for an index of 15. You can fix this two ways, the first is to use a regular for loop:
for(int i=0; i < weight.Length; i++)
{
totalCostLabel.Text += weight[i];
}
This brings the second mistake. You aren't appending anything to your totalCostLabel in your code, you are just replacing the value. This will append all the values of weight together as one.
Another way to do this is to use the foreach loop:
foreach(int i in weight)
{
totalCostLabel.Text += i;
}
This is the same as above but you don't have to worry about indexing.
Bottom line, even after you fix your loop, you will probably need to fix the way that the label takes the text otherwise you won't get your desired result.
Maybe you wanted something more like?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
btnAdd.Enabled = false;
}
int[] weight;
int entriesMade;
int numOfPackages;
private void btnReset_Click(object sender, EventArgs e)
{
if (int.TryParse(numEntriesBox.Text, out numOfPackages))
{
weight = new int[numOfPackages];
entriesMade = 0;
btnReset.Enabled = false;
btnAdd.Enabled = true;
totalCostLabel.Text = "";
}
else
{
MessageBox.Show("Invalid Number of Entries");
}
}
private void btnAdd_Click(object sender, EventArgs e)
{
int value;
if (int.TryParse(weightBox.Text, out value))
{
weight[entriesMade] = value;
weightBox.Clear();
totalCostLabel.Text = "";
int total = 0;
for (int i = 0; i <= entriesMade; i++)
{
total = total + weight[i];
if (i == 0)
{
totalCostLabel.Text = weight[i].ToString();
}
else
{
totalCostLabel.Text += " + " + weight[i].ToString();
}
}
totalCostLabel.Text += " = " + total.ToString();
entriesMade++;
if (entriesMade == numOfPackages)
{
btnAdd.Enabled = false;
btnReset.Enabled = true;
MessageBox.Show("Done!");
}
}
else
{
MessageBox.Show("Invalid Weight");
}
}
}
I need help with timer and List.
List consist of collection of string say 5 or 6 at a time. Now, I want to display string one on label1 and it should wait for 5s and then display string 2 on label1. I have timer control and I am specifying my code in timer_tick event.
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
int length = myStatus.Length;
for (int i = 0; i < length; i++)
{
string _myStatus = myStatus[i];
//label1.ResetText();
MessageBox.Show("Twitter Status =" + _myStatus);
//label1.Text = _myStatus;
//label1.Visible = true;
}
}
I have specify, Elapse = true and interval = 5000 but still I am not able to display one string at a time. In fact, I am getting last string only. I want to rotate the strings all time.
Can anyone help me.
That's because you're looping through all the strings each time the timer event fires.
Store your index in a private variable and use that instead.
private int _index = 0;
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
string _myStatus = myStatus[_index];
//label1.ResetText();
MessageBox.Show("Twitter Status =" + _myStatus);
//label1.Text = _myStatus;
//label1.Visible = true;
if(_index == (myStatus.Length - 1))
_index = 0;
else
_index++;
}
Well it is doing just what you told it to. However, what you told it to do is not what you meant for it to do. Try this.
public class Form1 : Form {
private string[] statuses = { "A", "B", "C", "D", "E" }; // Init with proper values somewhere
private int index = 0;
private void OnTimerTick(object sender, EventArgs e) {
string status = statuses[index];
index++;
if (index == statuses.Length) { // If index = Array.Length means we're
// outside bounds of array
index = 0;
}
}
}
I'd create an int outside of the Tick to hold your position. Make sure you reset it back to 0 when you restart the process.
int MyPosition = 0;
private void timer1_Tick(object sender, EventArgs e)
{
string[] myStatus = myStatusCollection.ToArray();
int length = myStatus.Length;
if((MyPosition + 1) > length)
{
//Index Out of Range
}
else
{
string _myStatus = myStatus[MyPosition];
label1.Text = _myStatus
}
MyPosition++;
}