I have an array in C# that generates random array of length 5. I have already declared this way
int[] array = new int[5]
I'm supposed to search for an array, an input dialog box opens, and I type in any value. It is supposed to give me an output if the number is found or else display not found and keep on going till I input the correct number.
I have this code something like this, it gives me some values not the kind i need. How can i implement such that it satisfies my condition? Thanks in advance.
private void btnSearch_Click(object sender, EventArgs e)
{
//use InputBox dialog to input a value.
//Search for the value in the array.
//If found, display "Found!", otherwise
//display "Not found!" when there is no match.
for (int i = 0; i < array.Length; i++)
{
InputBox inputDlg = new InputBox("Search for array value " + (i + 1));
if (inputDlg.ShowDialog() == DialogResult.OK)
{
if (array[i] == Array.IndexOf(array, 5))
{
array[i] = Convert.ToInt32(inputDlg.Input);
}
tbxOutput.AppendText("Value found: " + array[i] + Environment.NewLine);
}
else
{
tbxOutput.AppendText("Value not found" + Environment.NewLine);
}
}
If I understand correctly you have 1 array with 5 values in it, and you want to check if it contains a given value. Is that correct?
If yes you have to loop through your array and flag a boolean to true if you find it:
private void btnSearch_Click(object sender, EventArgs e) {
// loop until you call break
while(true) {
// ask for a value
InputBox inputDlg = new InputBox("Search for array value " + (i + 1));
try {
int value = Convert.ToInt32(inputDlg.Input);
// Check if value is in the array and display the appropriate message
if(isInArray(array, value)) {
tbxOutput.AppendText("Value found: " + value + Environment.NewLine);
// break to exit from the while loop
break;
} else {
tbxOutput.AppendText("Value not found" + Environment.NewLine);
}
} catch (OverflowException) {
tbxOutput.AppendText("OverflowException parsing input to int" + Environment.NewLine);
} catch (FormatException) {
tbxOutput.AppendText("FormatException parsing input to int" + Environment.NewLine);
}
}
}
The isInArray method:
// this method returns true if the given value is in the array
private static boolean isInArray(int[] array, int valueToFind) {
boolean found = false;
int currentValue;
for (int i = 0; i < array.Length; i++) {
currentValue = array[i];
if(currentValue == valueToFind) {
found = true;
break;
}
}
return found;
}
Related
I'm having a problem on an assignment, I can't clear the array. Also in my MessageBox when it displays the scores I get a zero as the first number no matter what I do. I can't figure out what to change so zero is not the first element.
public partial class Form1 : Form
{
int scoreTotal = 0;
int scoreCount = 0;
decimal average = 0;
int[] scoreTotalArray = new int[1];
public Form1()
{
InitializeComponent();
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (IsValidData())
{
Int32 score = Convert.ToInt32(txtScore.Text);
scoreTotalArray[scoreCount] = score;
Array.Resize(ref scoreTotalArray, scoreTotalArray.Length + 1);
scoreTotal += score; //accumulator
scoreCount++; //counter
average = scoreTotal / (decimal)scoreCount;//average
txtScoreCount.Text = scoreCount.ToString();//display in score count txtbox
txtScoreTotal.Text = scoreTotal.ToString(); //display in score total txtbox
txtAverage.Text = average.ToString("n2"); //display in average text box
txtScore.Clear();
txtScore.Focus();
}
}
catch (Exception ex) //catches all other exceptions
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
}
public bool IsValidData()
{
return
IsPresent(txtScore, "Score:") &&
IsInt32(txtScore, "Score:") &&
IsWithinRange(txtScore, "Score:", 0, 100);
}
public bool IsPresent(TextBox textBox, string name)
{
if (textBox.Text == "")
{
MessageBox.Show(name + " is a required field, please enter a number between 0 and 100.", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
public bool IsInt32(TextBox textBox, string name)
{
try
{
Convert.ToInt32(textBox.Text);
return true;
}
catch (FormatException)
{
MessageBox.Show(name + "must be a number between 0 and 100.", "Entry Error");
textBox.Focus();
return false;
}
}
public bool IsWithinRange(TextBox textBox, string name, decimal min, decimal max)
{
decimal number = Convert.ToDecimal(textBox.Text);
if (number < min || number > max)
{
MessageBox.Show(name + " must be between " + min + " and " + max + ".", "Entry Error");
textBox.Focus();
return false;
}
return true;
}
private void btnDisplayScore_Click(object sender, EventArgs e)
{
Array.Sort(scoreTotalArray);
string scoreCountString = "\n";
for(int i = 0; i < scoreCount; i++)
scoreCountString += scoreTotalArray [i] + "\n";
MessageBox.Show(scoreCountString + "\n", "Sorted Scores");
}
private void btnClearScores_Click(object sender, EventArgs e)
{
txtScore.Clear();
txtScoreTotal.Clear();
txtScoreCount.Clear();
txtAverage.Clear();
txtScore.Focus();
}
Your int array scoreTotalArray is always one element to big. That extra element contains the 0 you want to get rid of ;-)
Clearing the scores can be done by resizing your array to 0.
That said: You should probably consider using a List instead of an int array.
I'm in my second quarter of c # programming and i'm working on a POS application. I have my windows form created and I have my basic code done for the first week it was assigned. Now I have to "idiot-proof" my code by making sure that only correct data can be entered. Here's what I have so far:
private void btnAddItem_Click(object sender, EventArgs e)
{
//Declare variables
double dblSalesTax = 0, dblPrice, dblTax, dblSalesPrice;
string strItem, strTaxAdded;
int intQuantity;
bool diffTest = false;
//Process user input
while (!diffTest)
{
diffTest = double.TryParse(txtSalesTax.Text, out dblSalesTax);
}
while (dblSalesTax < 0 || dblSalesTax > 25)
{
MessageBox.Show("Please enter a valid tax.");
txtSalesTax.Clear();
diffTest = false;
}
intQuantity = Convert.ToInt16(txtQuantity.Text);
dblPrice = Convert.ToDouble(txtPrice.Text);
dblSalesPrice = dblPrice * intQuantity;
strItem = cbxItem.Text;
intQuantity = Convert.ToInt16(txtQuantity.Text);
dblSubtotal += dblSalesPrice;
if (chkTaxExempt.Checked)
{
dblTax = 0;
strTaxAdded = "";
}
else
{
dblTax = dblSalesPrice * dblSalesTax;
strTaxAdded = "*";
}
dblTaxTotal += dblTax;
lbxTally.Items.Add(strItem + ", " + dblSalesPrice.ToString("C") + strTaxAdded);
//Reset Form
txtPrice.Clear();
txtQuantity.Clear();
chkTaxExempt.Checked = false;
cbxItem.Focus();
}
private void btnEndSale_Click(object sender, EventArgs e)
{
dblGrandTotal = dblSubtotal + dblTaxTotal;
lbxTally.Items.Add("");
lbxTally.Items.Add("");
lbxTally.Items.Add("Subtotal: " + dblSubtotal.ToString("C"));
lbxTally.Items.Add("Tax Total: " + dblTaxTotal.ToString("C"));
lbxTally.Items.Add("Grand Total: " + dblGrandTotal.ToString("C"));
}
private void btnPay_Click(object sender, EventArgs e)
{
double dblPay, dblChange;
dblPay = Convert.ToDouble(txtPay.Text);
dblChange = dblPay - dblGrandTotal;
lbxTally.Items.Add("");
lbxTally.Items.Add("Amount Paid: " + dblPay.ToString("C"));
lbxTally.Items.Add("Change: " + dblChange.ToString("C"));
}
Variables being declared beforehand and diffTest being initialized as false.
The assignment is to make sure that the sales tax entered is between 0 and 25 and that they can't enter words or anything else. I thought I did it right but when I run it, I have an infinite loop on my message box and I can't figure out how to get out of it correctly (entering break just gets me out but keeps the input). I have google'd to my hearts content but haven't found a solution but I feel like it's because my code is reusing what's in the text box automatically (I could be very wrong!). Once I get this i'll have to "idiot-proof" my other inputs but I haven't tried yet cause I'm still stuck on this first one. I'm a beginner programming student so any help is appreciated.
You don't need a while statement there. Change it to:
if (dblSalesTax < 0 || dblSalesTax > 25)
Because you have there a while loop as soon as you step into that loop you will never get out because your condition will be always true.
My guess is that you should change While to If.
private void btnAddItem_Click(object sender, EventArgs e)
{
//Declare variables
double dblSalesTax = 0, dblPrice, dblTax, dblSalesPrice;
string strItem, strTaxAdded;
int intQuantity;
bool diffTest = false;
//Process user input
//While (!diffTest)
//{
diffTest = double.TryParse(txtSalesTax.Text, out dblSalesTax);
//}
// Check if the value gets parsed and is in range, otherwise show error and
//exit from this handler
If (!diffTest || dblSalesTax < 0 || dblSalesTax > 25) '<--- Change While to If
{
MessageBox.Show("Please enter a valid tax.");
txtSalesTax.Clear();
diffTest = false;
return; // Return from here since validation failed
}
...
...
...
}
May you can try using Parallel.Invoke(() => DoSomeWork(), () => DoSomeOtherWork()); withawait for the the task that has your loop, something like below:
Parallel.Invoke(
() =>
{
Console.WriteLine("Begin first task...");
}, // close first Action
async () =>
{
Console.WriteLine("Begin second task...");
while (true)
{
// HERE you are the code you need to be executed in infinite loop
await Task.Delay(60000);
}
}, //close second Action
() =>
{
Console.WriteLine("Begin third task...");
} //close third Action
); //close parallel.invoke
Console.WriteLine("Returned from Parallel.Invoke");
i was doing a ITP assignment, when i got an error. The code for the part with the problem is:
private void btnAddWord_Click(object sender, EventArgs e)
{
//if the textbox is empty
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
}
//if the number of items in the listbox is greater than 29
else if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
}
//error message for entering word that is already in the list
bool contains = false;
for (int i = 0; i < lbxUnsortedList.Items.Count; i++)
{
if (lbxUnsortedList.Items[i].ToString().ToLower() == this.tbxAddWord.Text.ToString().ToLower())
{
contains = true;
}
}
//if there is no match in the list
if (!contains)
{
//add word to the listbox
lbxUnsortedList.Items.Add(tbxAddWord.Text);
//update tbxListBoxCount
tbxListboxCount.Text = lbxUnsortedList.Items.Count.ToString();
//onclick, conduct the bubble sort
bool swapped;
string temp;
do
{
swapped = false;
for (int i = 0; i < lbxUnsortedList.Items.Count - 1; i++)
{
int result = CarNameData[i].ToString().CompareTo(CarNameData[i + 1]);
if (result > 0)
{
temp = CarNameData[i];
CarNameData[i] = CarNameData[i + 1];
CarNameData[i + 1] = temp;
swapped = true;
}
}
} while (swapped == true);
tbxAddWord.Text = "";
}
// if there is a match in the list
else
{
MessageBox.Show("The word that you have added is already on the list");
tbxAddWord.Text = "";
tbxAddWord.Focus();
}
}
When i leave the textbox blank and click the add button, it comes up with the error message, but still adds a blank space. how do i stop this from happening?
You need to return from the method if you don't want to execute more code:
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
return;
}
//if the number of items in the listbox is greater than 29
else if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
return;
}
First thing is if you are using CarNameData list as Generic collection list List<string> its allows inbuilt sort method like CarNameData.Sort();
Second thing you have to put your code in else part like this
private void btnAddWord_Click(object sender, EventArgs e)
{
//if the textbox is empty
if (string.IsNullOrEmpty(tbxAddWord.Text))
{
MessageBox.Show("You have entered no characters in the textbox.");
tbxAddWord.Focus();
}
else
{
//if the number of items in the listbox is greater than 29
if (lbxUnsortedList.Items.Count > 29)
{
MessageBox.Show("You have exceeded the maximum number of words in the list.");
tbxAddWord.Text = "";
}
//error message for entering word that is already in the list
bool contains = false;
for (int i = 0; i < lbxUnsortedList.Items.Count; i++)
{
if (lbxUnsortedList.Items[i].ToString().ToLower() == this.tbxAddWord.Text.ToString().ToLower())
{
contains = true;
}
}
//if there is no match in the list
if (!contains)
{
//add word to the listbox
lbxUnsortedList.Items.Add(tbxAddWord.Text);
//update tbxListBoxCount
tbxListboxCount.Text = lbxUnsortedList.Items.Count.ToString();
//onclick, conduct the bubble sort
bool swapped;
string temp;
do
{
swapped = false;
for (int i = 0; i < lbxUnsortedList.Items.Count - 1; i++)
{
int result = CarNameData[i].ToString().CompareTo(CarNameData[i + 1]);
if (result > 0)
{
temp = CarNameData[i];
CarNameData[i] = CarNameData[i + 1];
CarNameData[i + 1] = temp;
swapped = true;
}
}
} while (swapped == true);
tbxAddWord.Text = "";
}
// if there is a match in the list
else
{
MessageBox.Show("The word that you have added is already on the list");
tbxAddWord.Text = "";
tbxAddWord.Focus();
}
}
}
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'm trying to add numbered list functionality to a text editor. RichTextbox already provides the SelectionBullet property to change a selection to a bulleted list. But i was unable to find a similar property to generate numbered list. Is there any standard way to create a numbered list on Richtextbox. If not, i would have to implement it myself so code snips that could help me do that will help, Thank you.
I know that a link is not gernerally accepted as a good answer, however the article RichTextBox with Search Line Numbering, Bulleting, Printing, Searching Support on CodeProject could probably help you out quite a bit with what you are looking for.
In this article, the author extends the RichTextBox control into something that can do what you are asking (and more), plus the code is posted there for all to see.
Well, i implemented it as follows.
private void btnNumbers_Click(object sender, EventArgs e)
{
string temptext = rtbMain.SelectedText;
int SelectionStart = rtbMain.SelectionStart;
int SelectionLength = rtbMain.SelectionLength;
rtbMain.SelectionStart = rtbMain.GetFirstCharIndexOfCurrentLine();
rtbMain.SelectionLength = 0;
rtbMain.SelectedText = "1. ";
int j = 2;
for( int i = SelectionStart; i < SelectionStart + SelectionLength; i++)
if (rtbMain.Text[i] == '\n')
{
rtbMain.SelectionStart = i + 1;
rtbMain.SelectionLength = 0;
rtbMain.SelectedText = j.ToString() + ". ";
j++;
SelectionLength += 3;
}
}
private void rtbMain_KeyDown(object sender, KeyEventArgs e)
{//this piece of code automatically increments the bulleted list when user //presses Enter key
int tempNum;
if (e.KeyCode == Keys.Enter)
try
{
if (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine()]))
{
if (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1]) && rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 2] == '.')
tempNum = int.Parse(rtbMain.Text.Substring(rtbMain.GetFirstCharIndexOfCurrentLine(),2));
else tempNum = int.Parse(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine()].ToString());
if (rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1] == '.' || (char.IsDigit(rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 1]) && rtbMain.Text[rtbMain.GetFirstCharIndexOfCurrentLine() + 2] == '.'))
{
tempNum++;
rtbMain.SelectedText = "\r\n" + tempNum.ToString() + ". ";
e.SuppressKeyPress = true;
}
}
}
catch{}
}
Here is my answer... which is easily readable and refineable. I took a much different approach but added the ability to remove the numbered list within the selection if it already exists. Please note that so far I have only lightly tested it and it seems to work good... but it may need further refinement.
private void btnOrdered_Click(object sender, EventArgs e)
{
string[] splitSelection = null;
// If selection split selection else split everything
if (this.txtCaptionEditor.SelectionLength > 0)
{
splitSelection = this.txtCaptionEditor.SelectedText.Replace("\r\n", "\n").Split("\n".ToCharArray());
}
else
{
splitSelection = this.txtCaptionEditor.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
}
bool Exists = false;
for (int i = 0; i < splitSelection.GetLength(0); i++)
{
// If Ordered List Allready exists in selection then remove else add
if (!string.IsNullOrEmpty(splitSelection[i]))
{
if (splitSelection[i].Substring(0, 2) == "1.") { Exists = true; }
}
}
for (int i = 0; i < splitSelection.GetLength(0); i++)
{
int lineCount = (i + 1);
if (Exists)
{
this.txtCaptionEditor.Text = this.txtCaptionEditor.Text.Replace(Convert.ToString(lineCount) + ". ", "");
}
else
{
if(!string.IsNullOrEmpty(splitSelection[i]))
{
this.txtCaptionEditor.Text = this.txtCaptionEditor.Text.Replace(splitSelection[i], Convert.ToString(lineCount) + ". " + splitSelection[i]);
}
}
}
}
private void txtCaptionEditor_KeyDown(object sender, KeyEventArgs e)
{
string[] splitSelection = this.txtCaptionEditor.Text.Replace("\r\n", "\n").Split("\n".ToCharArray());
if (e.KeyCode == Keys.Enter)
{
// Get Current Line Position
int currentLine = this.txtCaptionEditor.GetLineFromCharIndex(this.txtCaptionEditor.SelectionStart);
// Only Run if the previous line is greater than zero
if ((currentLine) >= 0)
{
// Loop through 100 possible numbers for match you can go higher
// If you think your numbered list could go above 100
for (int i = 0; i < 100; i++)
{
if (splitSelection[(currentLine)].Substring(0, 2) == Convert.ToString((i + 1)) + ".")
{
// If the substring of the current line equals a numbered list value.. enumerate next line
this.txtCaptionEditor.SelectedText = "\n" + (i + 2) + ". ";
e.SuppressKeyPress = true;
}
}
}
}
}