c# how to find the largest number of 4 text boxes/results - c#

I have 4 text boxes and i would like to find the largest number of the 4, what methods are there that isnt a loop, these text boxes are total scores from 4 teams, the last button is the box that will show the largest number
i have to enter each value (value 1 to 5) in each button, and the result is the largest number of the four, i will be making these values up
private void button1_Click(object sender, EventArgs e)
{
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int result = 0;
if (Int32.TryParse(textBox4.Text, out value1) && Int32.TryParse(textBox2.Text, out value2) && Int32.TryParse(textBox6.Text, out value3) && Int32.TryParse(textBox14.Text, out value4) && Int32.TryParse(textBox13.Text, out value5))
{
result = value1 + value2 + value3 + value4 + value5;
textBox21.Text = result.ToString();
}
}
private void button2_Click(object sender, EventArgs e)
{
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int result = 0;
if (Int32.TryParse(textBox11.Text, out value1) && Int32.TryParse(textBox10.Text, out value2) && Int32.TryParse(textBox9.Text, out value3) & Int32.TryParse(textBox8.Text, out value4) && Int32.TryParse(textBox15.Text, out value5))
{
result = value1 + value2 + value3 + value4 + value5;
textBox22.Text = result.ToString();
}
}
private void button3_Click(object sender, EventArgs e)
{
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int result = 0;
if (Int32.TryParse(textBox7.Text, out value1) && Int32.TryParse(textBox5.Text, out value2) && Int32.TryParse(textBox1.Text, out value3) & Int32.TryParse(textBox3.Text, out value4) && Int32.TryParse(textBox12.Text, out value5))
{
result = value1 + value2 + value3 + value4 + value5;
textBox23.Text = result.ToString();
}
}
private void button4_Click(object sender, EventArgs e)
{
int value1 = 0;
int value2 = 0;
int value3 = 0;
int value4 = 0;
int value5 = 0;
int result = 0;
if (Int32.TryParse(textBox20.Text, out value1) && Int32.TryParse(textBox19.Text, out value2) && Int32.TryParse(textBox18.Text, out value3) & Int32.TryParse(textBox17.Text, out value4) && Int32.TryParse(textBox16.Text, out value5))
{
result = value1 + value2 + value3 + value4 + value5;
textBox24.Text = result.ToString();
}
}
private void button5_Click(object sender, EventArgs e)

There are many ways to do this, however this might help you out
Make life easier with some short hand extension methods
Extension Methods
public static class TextBoxExtensions
{
public static int GetInt(this TextBox source)
{
// if TextBox null just return 0
if (source == null)
{
return 0;
}
// if it is a valid int, return it, otherwise return 0
// not we use string, in case someone put a space at the start or end
return int.TryParse(source.Text.Trim(), out var value) ? value : 0;
}
public static bool HasValidInt(this TextBox source)
{
// if TextBox null or its not an int return false
// otherwise return true
return source != null && int.TryParse(source.Text.Trim(), out var _);
}
}
Helper function to get Max
// helper function, this does not use a loop
// get the max of all textboxes
private int GetMax(params TextBox[] args)
{
return args.Where(x => x.HasValidInt()) // remove any invalid numbers
.Select(x => x.GetInt()) // project to int
.Max(); //get the max of all
}
Your existing code
using the extension methods
private void button4_Click(object sender, EventArgs e)
{
// this is just a better way to validate your text boxes with the extension method
if (textBox1.HasValidInt() && textBox2.HasValidInt() && textBox3.HasValidInt() && textBox4.HasValidInt())
{
// get the ints from all text boxes using extension method
var result = textBox1.GetInt() + textBox2.GetInt() + textBox3.GetInt() + textBox4.GetInt();
textBox6.Text = result.ToString();
}
}
Get max Version 1
This doesn't use a loop. However, does use Linq
private void button5_Click(object sender, EventArgs e)
{
// get the max of all textboxes using the helper method
textBox6.Text = GetMax(textBox1, textBox2, textBox3, textBox4).ToString();
}
Get max Version 2
This doesn't use a loop. However, does use Math.Max
private void button6_Click(object sender, EventArgs e)
{
// this is just a better way to validate your text boxes with the extension method
if (textBox1.HasValidInt() && textBox2.HasValidInt() && textBox3.HasValidInt() && textBox4.HasValidInt())
{
// use math to get the max
var result = 0;
result = Math.Max(result, textBox1.GetInt());
result = Math.Max(result, textBox2.GetInt());
result = Math.Max(result, textBox3.GetInt());
result = Math.Max(result, textBox4.GetInt());
textBox6.Text = result.ToString();
}
}
Additional Resources
Extension Methods (C# Programming Guide)
Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type. Extension methods are a special kind of
static method, but they are called as if they were instance methods on
the extended type. For client code written in C#, F# and Visual Basic,
there is no apparent difference between calling an extension method
and the methods that are actually defined in a type.
Getting Started with LINQ in C#
This section contains basic background information that will help you
understand the rest of the LINQ documentation and samples.
Int32.TryParse Method
Converts the string representation of a number to its 32-bit signed
integer equivalent. A return value indicates whether the operation
succeeded.
params (C# Reference)
By using the params keyword, you can specify a method parameter that
takes a variable number of arguments.
You can send a comma-separated list of arguments of the type specified
in the parameter declaration or an array of arguments of the specified
type. You also can send no arguments. If you send no arguments, the
length of the params list is zero.
Enumerable.Where Method (IEnumerable, Func)
Filters a sequence of values based on a predicate.
Enumerable.Select Method (IEnumerable, Func)
Projects each element of a sequence into a new form.
Enumerable.Max Method
Returns the maximum value in a sequence of values.
Math.Max Method
Returns the larger of two specified numbers.
Comment from IFebles
It also can be done with this (segmentating the TextBoxs within
panels):
var values = panel1.Controls.Cast<Control>()
.Where(obj => obj is TextBox)
.Select(obj => int.Parse(obj.Text))
.Max();
knowing that it can throw a FormatException if any input can't be parsed. Not as neat as the given answer, but also good to know.

Related

How to convert a string array to an int array

I have been trying to make a program in which, I add data of numbers but in texts, that these are added to a listbox and later make the sum of said values, only that they have explained to me that once the data has been added, now I must do a for loop to go through each data of the first array and thus be able to convert each one of them to a numeric value. Only when doing the conversion on the add button, it tells me that it is not in the correct format.
I declared the array in the public partial class like this: string [] array;
private void bt_capturar_Click(object sender, EventArgs e)
{
string datos = txb_numeros.Text;
arreglo = datos.Split(',');
lbx_elementos.Items.Clear();
foreach (string elementos in arreglo)
{
lbx_elementos.Items.Add(elementos);
}
}
private void bt_sumar_Click(object sender, EventArgs e)
{
int suma = 0;
for (int x = 0; x < arreglo.Length; x++)
{
int numero;
numero = int.Parse(arreglo[x]);
suma = suma + numero;
}
MessageBox.Show("La suma es igual a " + suma.ToString());
}
Often we query array with a help of Linq (note, that we use int.TryParse since some items can not represent any integer value)
using System.Linq;
...
private void bt_sumar_Click(object sender, EventArgs e)
{
int suma = arreglo.Sum(item => int.TryParse(item, out int v) ? v : 0);
MessageBox.Show($"La suma es igual a {suma}");
}
However, you can implement a simple loop:
private void bt_sumar_Click(object sender, EventArgs e)
{
int suma = 0;
foreach (string item in arreglo)
suma += int.TryParse(item, out int v) ? v : 0;
MessageBox.Show($"La suma es igual a {suma}");
}
Use Int32.TryParse instead
int numero;
bool success = Int32.TryParse(arreglo[x], out numero);
suma += success ? numero : 0;
If I understand correctly, you want to already validate the input or convert it in bt_capturar_Click?
In that case you can do the following:
private void bt_capturar_Click(object sender, EventArgs e)
{
string datos = txb_numeros.Text;
arreglo = datos
.Split(',')
.Select(Int32.Parse)
.ToArray();
// Or ignore invalid values:
//arreglo = datos
// .Split(',')
// .Select(s => Int32.TryParse(s, out int n) ? n : (int?)null)
// .Where(n => n != null)
// .ToArray();
lbx_elementos.Items.Clear();
foreach (string elementos in arreglo)
{
lbx_elementos.Items.Add(elementos.ToString()); // Maybe use AddRange?
}
}
private void bt_sumar_Click(object sender, EventArgs e)
{
MessageBox.Show("La suma es igual a " + arreglo.Sum());
}
}
Using the following simple code, you will resolve your problem easily.
string strInput = "1,2,3,4,5";
string[] arrInput = strInput.Split(',');
// convert a string array to an int array
int[] arrResult = Array.ConvertAll(arrInput, s => int.TryParse(s, out int t) ? t : 0);
// sum up an array of integers
int nSum = arrResult.Sum();
References:
Array.ConvertAll, int.TryParse, Enumerable.Sum

find the first element of an array that is not consecutive using web forms

E.g. If we have an array [1,2,3,4,6,7,8] then 1 then 2 then 3 then 4 are all consecutive but 6 is not, so that's the first non-consecutive number.
If the whole array is consecutive then return null .
The array will always have at least 2 elements 1 and all elements will be numbers. The numbers will also all be unique and in ascending order. The numbers could be positive or negative and the first non-consecutive could be either too. please help me finish this code i am new in programming. My code:
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace _2katas
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var input = this.txtInput.Text;
var numarray = input.Split(',');
int firstValue = Convert.ToInt32(numarray[0]);
for (var i = 0; i < numarray.Length; i++)
{
if (Convert.ToInt32(numarray[i]) - i != firstValue)
{
lblPrint.Text = "";
}
else
{
lblPrint.Text = "";
}
if (this.rdbConsecutive.Checked == true)
{
lblKataRunning.Text = "Consecutive";
}
else if (this.rdbStripCleaning.Checked == true)
{
lblKataRunning.Text = "Strip Cleaning";
}
}
}
}
}
Let's extract a method:
Find the first element of an array that is not consecutive ...
If the whole array is consecutive then return null
We can implement it like this:
private static string FirstInconsecutive(string data) {
var array = data.Split(',');
if (array.Length <= 0)
return null; //TODO: what shall we return on empty array?
if (!int.TryParse(array[0], out int delta))
return array[0];
for (int i = 1; i < array.Length; ++i)
if (!int.TryParse(array[i], out int value) || value - i != delta)
return array[i];
return null;
}
Usage:
string result = FirstInconsecutive(txtInput.Text);
Please note int.TryParse which helps to return the right answer "ABC" on an input like "1, 2, 3, ABC, 4, 6, 7, 8" (user input txtInput.Text can contain any string)
A linq solution just for the fun of it:
static int? FindFirstNonConsecutive(IEnumerable<int> arr)
{
var nonConsecutiveInfo =
arr.Select((i, index) => new {Index = index, Delta = i - index})
.FirstOrDefault(t => t.Delta != arr.First());
return nonConsecutiveInfo?.Delta + nonConsecutiveInfo?.Index;
}
Note that this will only work finding non consecutive numbers in ascending order as per requirements.
Two numbers are not consecutive if the left ones + 1 <> the right one.
Check with something like this, note that you have to change your boundary checks:
for (var i = 0; i < numarray.Length - 1; i++)
{
if (Convert.ToInt32(numarray[i]) + 1 != Convert.ToInt32(numarray[i+1]))
Update your condition as below for loop and it will work. I would suggest you to have separate function so that it could be reusable if needed elsewhere in code.
Here start your loop from i = 1 and compare numarray[i-1] + 1 != numarray[i] values.
You can convert your sting[] to int[] with var numarray = input.Split(',').Select(x => Convert.ToInt32(x)).ToArray(); and use it with IsConsecutive(numarray) as per button1_Click code.
You can get first non-consecutive value with minor modification in return type and return statement as shown in GetFirstNonConsecutiveValue().
public bool IsConsecutive(int[] numarray)
{
for (int i = 1; i < numarray.Length; i++)
{
if (numarray[i-1] + 1 != numarray[i])
{
return false;
}
}
return true;
}
public int? GetFirstNonConsecutiveValue(int[] numarray)
{
for (int i = 1; i < numarray.Length; i++)
{
if (numarray[i-1] + 1 != numarray[i])
{
return numarray[i];
}
}
return null;
}
private void button1_Click(object sender, EventArgs e)
{
var input = this.txtInput.Text;
var numarray = input.Split(',').Select(x => Convert.ToInt32(x)).ToArray();
var nonConsecutiveValue = GetFirstNonConsecutiveValue(numarray);
if (nonConsecutiveValue != null)
{
// nonConsecutiveValue is first non consecutive value.
}
else
{
// sequence is consecutive.
}
}
One way to go.
string rawData = "1,2,3,4,6,7,8,9";
IEnumerable<int> data = rawData.Split(',').Select(v => Convert.ToInt32(v));
IEnumerable<int> all = Enumerable.Range(data.Min(), data.Max() - data.Min() + 1);
IEnumerable<int> diff = all.Except(data);
if (diff.Count() == 0)
{
return null;
}
return data.ElementAt(all.ToList().IndexOf(diff.First()))
NB Not thoroughly tested.
Just test diff for being empty to get the numbers are consecutive

C# - How to add a number to a already existing number?

Basically my question is how i add to a number like a calculator does for example? My code currently looks like this but it does a add operation instead of adding the number behind the existing number.
private void button1_Click(object sender, RoutedEventArgs e)
{
value1 = value1 + 1;
output = value1;
textresult.Text = output.ToString();
if the user presses the button twice it would be 2. I want it to be 11. How do i do this?
You should use string variable instead int variable
int a = 1;
int b = 1;
int c = a+b;
The result of c is 2
string a = "1";
string b = "1";
string c = a+b;
If you use string it will be "11"

Stuck with two dimensional array

I'm trying to create a booking service and I've been stuck on this part for many hours and I just can't figure out what I'm doing wrong.
So I've got a Two Dimensional array and when trying to print out some stuff when testing and trying to figure out what's wrong, all I get is System.String[] which doesn't really make me any wiser. I want to be able to access the details in i.e. m_nameMatrix[0,0] to check whether the seat is reserved or not.
Here's a snippet from my form code:
private void UpdateGUI(string customerName, double price)
{
string selectedItem = cmdDisplayOptions.Items[cmdDisplayOptions.SelectedIndex].ToString();
rbtnReserve.Checked = true;
lstSeats.Items.Clear();
lstSeats.Items.AddRange(m_seatMngr.GetSeatInfoStrings(selectedItem));
}
And here are two methods from my 2nd class:
public string[] GetSeatInfoStrings(string selectedItem)
{
int count = GetNumOfSeats(selectedItem);
if (count <= 0)
{
return new string[0];
}
string[] strSeatInfoStrings = new string[count];
for (int index = 0; index <= count; index++)
{
strSeatInfoStrings[index] = GetSeatInfoAt(index);
}
return strSeatInfoStrings;
}
public string GetSeatInfoAt(int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string seatInfo = m_nameMatrix.GetValue(row, col).ToString();
return seatInfo;
}
I'm not actually getting an exception so it might be my logical thinking that's been taking a hit due to hours and hours of trying to figure it out.
EDIT:
public void ReserveSeat(string name, double price, int index)
{
int row = (int)Math.Floor((double)(index / m_totNumOfCols));
int col = index % m_totNumOfCols;
string reserved = string.Format("{0,3} {1,3} {2, 8} {3, 8} {4,22:f2}",
row + 1, col + 1, "Reserved", name, price);
m_nameMatrix[row, col] = reserved;
}
This line:
for (int index = 0; index <= count; index++)
should be:
for (int index = 0; index < count; index++)
Why? Lets say I have an array with 2 objects in it. count would be 2. However, the indexes are 0 and 1. So you have to use a less than operator.
If you're getting "System.String[]" in your messagebox, it's because you're trying to print a string[] directly, rather than the various strings it contains:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(data);
Instead, you need to show the contents of data:
string[] data = GetSeatInfoStrings("foo");
MessageBox.Show(string.Join("\n", data));
See here for the documentation.
Suppose you had a method called ReturnArray():
class Class2
{
public string[] ReturnArray()
{
string[] str = new string[] { "hello", "hi" };
return str;
}
}
If you called ReturnArray in your main class like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(class2.ReturnArray());
}
it will return System.String[] because MessageBox.Show(...) takes a string as an argument, in this case.
So you'll also get the same result by using MessageBox.Show(class2.ReturnArray().ToString());
Instead, you may want to do something like this:
Class2 class2 = new Class2();
private void button1_Click(object sender, EventArgs e)
{
string[] strArray = class2.ReturnArray();
listBox1.Items.AddRange(strArray);
}

"Input string was not in a correct format." for Convert() method

i have debugged my code (below) and found out the problem is the Convert() method that converts the text from the textbox. but how i fix this problem?
i have a example of similar problem here.
code:
//METHODS
static string RollDice (int dice)
{
Random roll = new Random();
int rollOutput = roll.Next(1, dice);
//NOTE: VERY IMPORTANT! EVERY TIME THE INPUT GOES INTO THIS
//METHOD REMEMBER TO INCREACE IT BY ONE!
//AND NEVER LET THE USER TO ROLL TO DICE QUICKLY ONE AFTER ANOTHER!
string rollResult = rollOutput.ToString();
return rollResult;
}
static void TwiceD20(int bonus, bool advantage)
{
string firstRollString = RollDice(21) + bonus;
string secondRollString = RollDice(21) + bonus;
int firstRoll = Convert.ToInt32(firstRollString);
int secondRoll = Convert.ToInt32(secondRollString);
switch(advantage)
{
case true:
if (firstRoll >= secondRoll)
{
MessageBox.Show(firstRollString);
}
else
{
MessageBox.Show(secondRollString);
}
break;
case false:
if (firstRoll <= secondRoll)
{
MessageBox.Show(firstRollString);
}
else
{
MessageBox.Show(secondRollString);
}
break;
}
}
//BUTTONS
private void btn1d20_Click(object sender, EventArgs e)
{
MessageBox.Show("Roll Result: " + RollDice(21));
}
private void btnAdv_Click(object sender, EventArgs e)
{
TwiceD20(Convert.ToInt32(textBox1d20.Text), true);
}
private void btnDisAdv_Click(object sender, EventArgs e)
{
TwiceD20(Convert.ToInt32(textBox1d20.Text), false);
}
You have added a non-int into the string. So naturally you cannot convert that to an int because the string is not just an int anymmore.
string firstRollString = RollDice(21) + bonus; // This won't convert back to an int
string secondRollString = RollDice(21) + bonus; // This won't convert back to an int
int firstRoll = Convert.ToInt32(firstRollString);
int secondRoll = Convert.ToInt32(secondRollString);
Adding bonus to the string result of RollDice is simply appending the string "True" or "False" to the result of RollDice. I suspect that you think it is adding a numerical 0 or 1.
I would do as the comments suggest and have RollDice return a number. Then you can turn it into a string and manipulate it later as you see fit.
Or, if you don't want to return anything, just make a quick change to the order of operations.
int firstRoll = Convert.ToInt32(RollDice(21));
int secondRoll = Convert.ToInt32(RollDice(21));
string firstRollString = firstRoll + bonus;
string secondRollString = secondRoll + bonus;
But, not knowing for sure what you intend for your code to do, even that may not work for you.

Categories