Checking input values with array contents in C#.net - arrays

I have an array with 5 integer values.
I need to check each value in it against input values from a text box.
A label displays a Value found message if the input value exists in the array.
If not, theValue not found message is displayed.
How do I display the Value not found message correctly?
Here's my code,
private void button1_Click(object sender, EventArgs e)
{
try
{
int[] id = { 1, 2, 3, 4, 5 };
int row;
int x = Convert.ToInt32(txtid.Text);
for (row = 0; row < id.Length; row++)
{
if (id[row] == x)
{
txtdesc.Text = "Value found!";
}
}
txtdesc.Text = "Value not found!";
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Without going into great detail, using a flag is the simplest way of tracking a Boolean state when you are first starting out.
private void button1_Click(object sender, EventArgs e)
{
try
{
int[] id = { 1, 2, 3, 4, 5 };
int row;
int x = Convert.ToInt32(txtid.Text);
bool found = false;
for (row = 0; row < id.Length; row++)
{
if (id[row] == x)
{
found = true;
}
}
txtdesc.Text = found ? "Value found!" : "Value not found!";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
With LINQ, these things get a lot easier:
// At the top of the file
using System.Linq;
private void button1_Click(object sender, EventArgs e)
{
try
{
int[] id = { 1, 2, 3, 4, 5 };
int x = Convert.ToInt32(txtid.Text);
txtdesc.Text = id.Contains(x) ? "Value found!" : "Value not found!";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}

private void button1_Click(object sender, EventArgs e)
{
try
{
int[] id = { 1, 2, 3, 4, 5 };
int row;
int x = Convert.ToInt32(txtid.Text);
for (row = 0; row < id.Length; row++)
{
if (id[row] == x)
{
txtdesc.Text = "Value found!";
return; //only add this line
}
}
txtdesc.Text = "Value not found!";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

Related

WPF list modification during iteration?

I'm trying to make a very simple game where the yellow ball bouncing back and fourth. If it collides with one of the moving blue squares, the square is supposed to disappear and a new one should appear (always 3 in the window) elsewhere. When my code reaches this part, all 3 squares disappear (then reappears as intended it is not a problem) and I just cant figure out why. It would be a huge help if somebody could run over my methods responsible for the problem. Thank you in advance.
So my timer_Tick method, responsible for every frame:
void timer_Tick(object sender, EventArgs e)
{
logic.MoveBall();
if (model.Enemy.Count<3)
{
logic.AddEnemy();
}
int iii = 0;
foreach (MyShape enemy in model.Enemy) //the whole thing from here is me trying to solve list modification during iteration
{
if (logic.MoveEnemy(enemy) == -1)
{
logic.MoveEnemy(enemy);
}
else iii = logic.MoveEnemy(enemy);
}
if (iii > -1)
{
for (int j = model.Enemy.Count - 1; j >= 0; j--)
{
if (j == model.Enemy.Count - iii)
{
model.Enemy.RemoveAt(j);
}
}
}
}
MoveEnemy: I try to decide whether there is collusion and if yes, then try to remove the given shape object (blue square). Because This whole method is in a foreach, I just save the removable element and forward it to timer_Tick
public int MoveEnemy(MyShape shape)
{
int i = 0;
int ii = -1;
if ((shape.Area.IntersectsWith(model.Ball.Area)))
{
i = 0;
foreach (var e in model.Enemy)
{
i++;
if (shape == e)
{
ii = i;
}
}
}
shape.ChangeX(shape.Dx);
shape.ChangeY(shape.Dy);
bool coll = false;
foreach (var e in model.Enemy)
{
if ((e.Area.IntersectsWith(shape.Area)) && (shape != e))
{
coll = true;
}
}
if (shape.Area.Left < 0 || shape.Area.Right > Config.Width-40 || coll)
{
shape.Dx = -shape.Dx;
}
if (shape.Area.Top < 0)
{
shape.Dy = -shape.Dy;
}
if (shape.Area.Bottom > Config.Height/2)
{
shape.Dy = -shape.Dy;
}
RefreshScreen?.Invoke(this, EventArgs.Empty);
return ii;
}
And finally AddEnemy:
public void AddEnemy()
{
rnd = new Random();
int r = rnd.Next(-300, 300);
model.Enemy.Add(new MyShape(Config.Width / 2+r, 0, 40, 40));
RefreshScreen?.Invoke(this, EventArgs.Empty);
}
List<T> (or IList and Enumerable) exposes some useful methods to compact code:
int itemIndex = list.IndexOf(item); // Gets the index of the item if found, otherwise returns -1
list.Remove(item); // Remove item if contained in collection
list.RemoveAll(item => item > 5); // Removes all items that satisfy a condition (replaces explicit iteration)
bool hasAnyMatch = list.Any(item => item > 5); // Returns true as soon as the first item satisfies the condition (replaces explicit iteration)
A simplified version, which should eliminate the flaw:
void timer_Tick(object sender, EventArgs e)
{
if (model.Enemy.Count < 3)
{
logic.AddEnemy();
}
logic.MoveBall();
model.Enemy.ForeEach(logic.MoveEnemy);
model.Enemy.RemoveAll(logic.IsCollidingWithBall);
}
public void AddEnemy()
{
rnd = new Random();
int r = rnd.Next(-300, 300);
model.Enemy.Add(new MyShape(Config.Width / 2 + r, 0, 40, 40));
RefreshScreen?.Invoke(this, EventArgs.Empty);
}
public bool IsCollidingWithBall(MyShape shape)
{
return shape.Area.IntersectsWith(model.Ball.Area);
}
public int MoveEnemy(MyShape shape)
{
shape.ChangeX(shape.Dx);
shape.ChangeY(shape.Dy);
bool hasCollision = model.Enemy.Any(enemy => enemy.Area.IntersectsWith(shape.Area)
&& enemy != shape);
if (hasCollision || shape.Area.Left < 0 || shape.Area.Right > Config.Width - 40)
{
shape.Dx = -shape.Dx;
}
if (shape.Area.Top < 0)
{
shape.Dy = -shape.Dy;
}
if (shape.Area.Bottom > Config.Height / 2)
{
shape.Dy = -shape.Dy;
}
RefreshScreen?.Invoke(this, EventArgs.Empty);
}

Passing an array between forms C++ CLR

I'd like to pass a generated array (arNum[20]) from Form number 1(MyForm.h) to Form number 2(MyForm1.h) in the following function
private: System::Void button1_Click(System::Object^ sender, System::EventArgs^ e) {
int x;
int arNum[20];
if (!int::TryParse(txtNodes->Text, x))
MessageBox::Show("First box wasn't an integer");
else
{
for (int i = 0; i < txtNumbers->Text->Length; i+=2)
{
if (!(int)txtNumbers->Text[i])
{
MessageBox::Show("Invalid Input!");
return;
}
else
{
arNum[i] = (int)txtNumbers->Text[i];
}
}
MessageBox::Show("Data submitted correctly.");
MyForm1 ^form = gcnew MyForm1();
form->
}
}
Thanks.

Arrays with methods

i try to write on label an array with methods. When i try to put values of array it writes system int 32 on label, here is the code and how can put values on label
p.s. sorry about bad English
enter code here void arr_5( int[] mas5)
{
for (int i=0, j=5; i<10; i++, j+=5)
{
mas5[i] = j;
}
}
private void button1_Click(object sender, EventArgs e)
{
int[] a = new int[10];
arr_5 (a);
label1.Text += a.ToString() + " ";
}
That's because an array contains more than one value and in order to show it you could do something like:
int[] arr_5( int[] mas5)
{
for (int i=0, j=5; i<10; i++, j+=5)
{
mas5[i] = j;
}
return mas5;
}
private void button1_Click(object sender, EventArgs e)
{
int[] a = new int[10];
arr_5 (a);
String label="";
for(int i=0; i<a.length; a++)
{
label= label + a +" ";
}
label1.Text =label;
}
Please be aware that i've changed your arr_5 to return the newly created array.

Naudio unvalid operation exception unhandeled

I am using Naudio in WPF for the first time.It keeps giving an exception "InvalidOperationException was unhandled".Buffer Bull.I don't know how to handle it. So far there is no error that is being shown by the debugger.
The Lines that are throwing the exception
waveFile.Write(e.Buffer, 0, e.BytesRecorded); and
sourceStream.StartRecording();
public partial class voiceNote : Window
{
public voiceNote()
{
InitializeComponent();
}
public NAudio.Wave.WaveIn waveSource = null;
public NAudio.Wave.WaveFileWriter waveFile = null;
private void resources_Click(object sender, RoutedEventArgs e)
{
List<NAudio.Wave.WaveInCapabilities> sources = new List<NAudio.Wave.WaveInCapabilities>();
for (int i = 0; i < NAudio.Wave.WaveIn.DeviceCount; i++)
{
sources.Add(NAudio.Wave.WaveIn.GetCapabilities(i));
}
//to make sure refreshed
devicesList.Items.Clear();
foreach (var source in sources)
{
//ListViewItem item;
devicesList.Items.Add(source.ProductName);
//= new ListViewItem(source.ProductName.ToString);
//item.SubItem.Add(new ListViewItem.ListViewSubItem(item, source.Channels, ToString()));
//sourceList.Items.Add(item);
}
}
//to get input....Sound Source
NAudio.Wave.WaveIn sourceStream = null;
//To sync the source of input and input audio
NAudio.Wave.DirectSoundOut waveOut = null;
// To write wve file
NAudio.Wave.WaveFileWriter waveWriter = null;
private void startRecording_Click(object sender, RoutedEventArgs e)
{
// if (devicesList.SelectedItem.Count = 0) return;
int devicenumber = devicesList.SelectedIndex;
// int devicenumber = devicesList.SelectedItems[0].index;
sourceStream = new NAudio.Wave.WaveIn();
sourceStream.DeviceNumber = devicenumber;
sourceStream.WaveFormat = new NAudio.Wave.WaveFormat(44100, NAudio.Wave.WaveIn.GetCapabilities(devicenumber).Channels);
NAudio.Wave.WaveInProvider waveIn = new NAudio.Wave.WaveInProvider(sourceStream);
//*****************************
//waveOut = new NAudio.Wave.DirectSoundOut();
//waveOut.Init(waveIn);
//sourceStream.StartRecording();
//waveOut.Play();
sourceStream.DataAvailable += new EventHandler<NAudio.Wave.WaveInEventArgs>(sourceStream_DataAvailable);
// waveWriter = new NAudio.Wave.WaveFileWriter(sav.FileName, sourceStream.WaveFormat);
sourceStream.StartRecording();
}
private void sourceStream_DataAvailable(object sender, NAudio.Wave.WaveInEventArgs e)
{
// //data is byte array, buffer, count
// waveWriter.WriteData(e.Buffer, 0, e.BytesRecorded);
// waveWriter.Flush(); //to write on disk.... so data is not held up on the ram
}
private void stopandsave_Click(object sender, RoutedEventArgs e)
{
if (waveOut != null)
{
waveOut.Stop();
waveOut.Dispose();
waveOut = null;
}
//Stop Recording
if (sourceStream != null)
{
sourceStream.StartRecording();
sourceStream.Dispose();
sourceStream = null;
}
if (waveWriter != null)
{
waveWriter.Dispose();
waveWriter = null;
}
}
}

Import Data into 2d Array from .txt

I am having trouble creating a method to import data from a txt file into a 1d string array and a 2d double array.
Here is what I have thus far:
public static void main(String[] args){
String[] productName = new String[100];
double[][] sales = new double[100][5];
initializeArrays(productName, sales);
....}
public static void initializeArrays(String a[], double b[][]){
try
{
String output = "";
File inputFile = new File("c:/temp/salesdata.txt");
if (inputFile.exists())
{
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNext())
{
for (i=1;i<6;i++)
{
b[a.length][i]=scanner.nextDouble();
}
rowCount += 1;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Error reading file: ");
}
Try this code:
public static void initializeArrays(String a[], double b[][]){
try
{
String output = "";
File inputFile = new File("c:/temp/salesdata.txt");
int counter = 0;
if (inputFile.exists())
{
Scanner scanner = new Scanner(inputFile);
while (scanner.hasNext())
{
for (i=1;i<6;i++)
{
b[counter][i]=scanner.nextDouble();
}
counter++;
rowCount += 1;
}
}
}
catch (FileNotFoundException e)
{
System.out.println("Error reading file: ");
}

Resources