I have an array:
class Words
{
public static string[] wordsArray = { "one", "two", "three", "four" };
}
TextBlock which displays an array of values, and button that displays the next value of the array:
private int counter = 0;
private void goButton_Click(object sender, RoutedEventArgs e)
{
if (counter < Words.wordsArray.Length)
{
enWordTextBlock.Text = Words.wordsArray[counter++];
}
}
When the box appears on the last value of the array, the program will continue to not work, how to make it work in a "circle"?
Thanks all!
This should work:
private void goButton_Click(object sender, RoutedEventArgs e)
{
counter++; //increase the counter
int i = counter % Words.wordsArray.Length; //modulo operation
enWordTextBlock.Text = Words.wordsArray[i]; //set text
}
private int counter = 0;
private void goButton_Click(object sender, RoutedEventArgs e)
{
enWordTextBlock.Text = Words.wordsArray[counter++ % Words.wordsArray.Length];
}
[Edit]
Ok, this is an edit related to user1397396 comment. I'm not sure I understand you correctly, but you might have a problem with negative value modulus. For example:
int counter = 0;
int mod = 4;
counter--; // counter is -1 after this line is executed
int result = counter % mod; // result is -1
result = (counter + mod) % mod; // result is now 3 as desired
Here is how I would implement these Next and Previous buttons.
private int counter = 0;
private void NextButton_Click(object sender, RoutedEventArgs e)
{
enWordTextBlock.Text = Words.wordsArray[counter % Words.wordsArray.Length];
counter++; // put ++ operator in new line to avoid confusion
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
int wordCount = Words.wordsArray.Length;
// add wordCount before applying modulus (%) to avoid negative results
// -1 % 5 = -1; -2 % 5 = -2; -6 % 5 = -1 etc
// negative values would cause exception when accessing array
counter = ((counter - 1) + wordCount) % wordCount;
enWordTextBlock.Text = Words.wordsArray[counter];
}
For example, this code would cause pressing Next, Previous, Next to give you this: "one", "four", "one".
Even better solution would be to use a method (or to inline code) such as this:
private static int GetPositiveIntModulus(int value, int mod)
{
return ((value % mod) + mod) % mod;
}
It will give you a positive result for any value, even when value < -mod. So you could write the code above like this:
private int counter = 0;
private void NextButton_Click(object sender, RoutedEventArgs e)
{
// uncomment this to ensure valid counter
// if it is changed somewhere else in the program
//counter = GetPositiveIntModulus(counter, Words.wordsArray.Length);
enWordTextBlock.Text = Words.wordsArray[counter];
counter = GetPositiveIntModulus(counter + 1, Words.wordsArray.Length);
}
private void PreviousButton_Click(object sender, RoutedEventArgs e)
{
counter = GetPositiveIntModulus(counter - 1, Words.wordsArray.Length);
enWordTextBlock.Text = Words.wordsArray[counter];
}
Related
I am trying to write a program that uses recursion to cycle through a given value and print it in order into a listbox. The output is supposed to look like this when I use 5 for n:
1 2 3 4 5
However, I cannot figure out a way to make my program work, and any other sources I get only use console functions.
Down below is the code I have so far. I would appreciate any help I can get with this.
private void button1_Click(object sender, EventArgs e)
{
int n;
n = Convert.ToInt32(textBox1.Text);
int print = Print(1, n);
listBox1.Items.Add(print);
}
private static int Print(int order, int n)
{
if (n < 1)
{
return order;
}
n--;
return Print(order + 1, n);
}
Well, I'm not able to test this out right now, but I hope I have made the concept clear.
Something like this should do the work:
private void button1_Click(object sender, EventArgs e)
{
int n;
n = Convert.ToInt32(textBox1.Text);
PrintToListBox(listBox1, 1, n);
}
private static void PrintToListBox(ListBox listBox, int frm, int to)
{
listBox1.Items.Add(frm);
if (frm + 1 <= to)
{
PrintToListBox(listBox1, frm + 1, n);
}
return;
}
I would write it as:
private void button1_Click(object sender, EventArgs e)
{
listBox1.Items.Clear();
PrintToListBox(listBox1, 1, 5);
}
private void PrintToListBox(ListBox lb, int n, int max)
{
if (n <= max)
{
lb.Items.Add(n);
PrintToListBox(lb, n+1, max);
}
}
Hello I'm still new to programming and yes this is not the best code you will see... I tried making calculator on C# windows form for fun and I'm having trouble on the subtraction and division operations, but the addition and multiplication works perfectly fine for me. I decided to have a list array so that I would be able to input numbers as much as I want.
The error for the subtraction is when I input for example 5 - 2 the result will be -3
As for the division the error is that the result is always 1
Please tell me where did I go wrong and give a detailed explanation if possible so that I would understand more about programming. Thanks in advance!
namespace CalculatorTestForm1
{
public partial class Form1 : Form
{
public static List<int> Numlist = new List<int>();
public static string operation;
public Form1()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
Button Num = (Button)sender;
TXTBox.Text += Num.Text;
}
private void BPlus_Click(object sender, EventArgs e)
{
operation = "add";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BEquals_Click(object sender, EventArgs e)
{
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
int sum = 0;
int product = 1;
int quotient = 1;
int difference = 0;
if (operation == "add"){
foreach (int value in Numlist)
{
sum += value;
}
string Answer = sum.ToString();
TXTBox.Text = Answer;
}else if(operation == "minus"){
foreach (int value in Numlist)
{
difference = value - difference;
}
string Answer = difference.ToString();
TXTBox.Text = Answer;
}
else if (operation == "multiply")
{
foreach (int value in Numlist)
{
product *= value;
}
string Answer = product.ToString();
TXTBox.Text = Answer;
}
else if (operation == "divide")
{
foreach (int value in Numlist)
{
quotient = value / value;
}
string Answer = quotient.ToString();
TXTBox.Text = Answer;
}
Numlist.Clear();
}
private void BClear_Click(object sender, EventArgs e)
{
TXTBox.Text = "";
Numlist.Clear();
}
private void BMinus_Click(object sender, EventArgs e)
{
operation = "minus";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BDivide_Click(object sender, EventArgs e)
{
operation = "divide";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
private void BMulti_Click(object sender, EventArgs e)
{
operation = "multiply";
int AddNum = Convert.ToInt32(this.TXTBox.Text);
Numlist.Add(AddNum);
TXTBox.Text = "";
}
}
}
For the division it's obvious:
quotient = value / value;
value/value will always be 1.
There must be quotient in that loop somewhere...
For the subtraction the problem is that because of the way you do it, the order of the numbers are reversed.
lets say 5 - 2:
foreach (int value in Numlist)
{
difference = value - difference;
}
NumList = {5,2}
1st iteration:
difference = value(5) - difference(0) = 5
2nd iteration:
difference = value(2) - difference(5) = -3
You should reverse the order of the loop: NumList.Reverse()
And for the division as well:
Division:
foreach (int value in Numlist.Reverse())
{
quotient = value / quotient;
}
Subtraction:
foreach (int value in Numlist)
{
difference = value - difference;
}
I am trying to make my button take input from a textbox and add it to the index. The problem is that with everything I have tried, I cannot get it to give a unique value to each position in the index.
private void addBtn_Click(object sender, EventArgs e)
{
for (int i = 0; i < nums.Length; i++)
{
if (nums[0] == 0)
{
nums[0] = int.Parse(inputText.Text);
i++;
}
if (nums[1] == 0)
{
nums[1] = int.Parse(inputText.Text);
i++;
}
}
MessageBox.Show(nums[i].ToString());
}
Right now my code inserts the value to both index positions instead of assigning a value to position 0 and then allowing the user to insert a different value into position 1 and so on and so on.
It's not clear what your intent is, but it looks like you might be trying to add numbers to an array. This code will assign the parsed string to the first item in the array that isn't zero.
private void addBtn_Click(object sender, EventArgs e)
{
int i = 0;
for (; i < nums.Length; i++)
{
if (nums[i] == 0)
{
nums[i] = int.Parse(inputText.Text);
break;
}
}
MessageBox.Show(nums[i].ToString());
}
But this would be a better way, because the user might type "0":
private int _lastUsedIndex = -1;
private void addBtn_Click(object sender, EventArgs e)
{
var number = int.Parse(inputText.Text);
// Increment by one
++_lastUsedIndex;
nums[_lastUsedIndex] = number;
MessageBox.Show(number.ToString());
}
But still, arrays aren't a great idea: They can't grow as you add things. First they're bigger than you need, then suddenly they're too small and you crash. We have better options now. Unless your teacher insists that you must use an array, use List<int> instead. In this version, we'll also use a different way to parse the number, which won't crash if the user types "LOLWUT?!?!" instead of a number:
private List<int> nums = new List<int>();
private void addBtn_Click(object sender, EventArgs e)
{
int number;
if (int.TryParse(inputText.Text, out number))
{
nums.Add(number);
MessageBox.Show(number.ToString());
}
else
{
MessageBox.Show(inputText.Text + " isn't a number, smart guy.");
}
}
I have a combobox with the items
1
2
3
...
40
,if I chose the value 4 then I should be able to add in my listbox no more than 4 values.This is what i was thinking of but isn't working.
public Form1()
{
InitializeComponent();
}
private void add_Click(object sender, EventArgs e)
{
int allowedItemsCount = 0;
Int32.TryParse(comboBox1.SelectedText, out allowedItemsCount);
int currentItemsCount = listBox1.Items.Count;
if (currentItemsCount < allowedItemsCount)
{
listBox1.Items.Add(textBox1.Text);
}
}
private void delete_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItems.Count != 0)
{
while (listBox1.SelectedIndex != -1)
{
listBox1.Items.RemoveAt(listBox1.SelectedIndex);
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedText, out x);
int count = listBox1.Items.Count;
if (count > x)
{
listBox1.Items.Clear();
int difference = count - x;
for (int i = 0; i < difference; i++)
{
listBox1.Items.RemoveAt(listBox1.Items.Count - 1);
}
}
}
}
Here is the full code you asked for but is not working...now the add button is not working.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedText, out x);
int count = listBox1.Items.Count;
if (count > x)
{
listBox1.Items.Clear();
int difference = count - x;
for(int i = 0 ; i < difference ; i++)
{
listBox1.Items.RemoveAt(listBox1.Items.Count-1);
}
}
}
Update
As per your comment, write this code in your add button click event
int allowedItemsCount = 0;
Int32.TryParse(comboBox1.SelectedText, out allowedItemsCount);
int currentItemsCount = listBox1.Items.Count;
if(currentItemsCount < allowedItemsCount)
{
listBox1.Items.Add(textBox1.Text); // I assume your textbox id is TextBox1
}
For removing extra items:
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
listBox1.TrimExcess(Int32.Parse(comboBox1.SelectedText));
//If you control the items on the combo so you know for sure the parse will work, ignore the tryparse
}
And for adding items to the ListBox (and control it does not have to much items:
private int addToListBox(object item)
{
if(listbox1.items.count>=Int32.Parse(comboBox1.SelectedText)) return -1;
listbox1.items.add(item);
return 0;
}
And when you need to add to that listbox use addToListBoxand not listbox1.items.add
This will check if you can add line to listbox1 and if its changed number of line it will delete it.
Adding is made by button.
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedItem.ToString(), out x);
int count = listBox1.Items.Count;
while(count > x){
listBox1.Items.RemoveAt(count - 1);
count = listBox1.Items.Count;
}
}
private void button2_Click(object sender, EventArgs e)
{
int x = 0;
Int32.TryParse(comboBox1.SelectedItem.ToString(), out x);
if (listBox1.Items.Count < x)
{
listBox1.Items.Add(x); //add whatever you want
}
}
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++;
}