How to get accumulated value of TextBox in WFA (.NET)? - c#

I'm trying to create a program that requires about three textbox values. Those values will then get added to display their total. Example:
int input1 = 1;
int input2 = 1;
int input3 = 1;
totalInput = input1 + input2 + input3;
As previously mentioned, they get added.
1st run: 3; // with values of 1, 1, 1
2nd run: 6; // with values of 2, 2, 2
3rd run: 9; // with values of 3, 3, 3
Good so far
However, I'm trying to create a running total to display it in my form. I do that by using the operator of += . Take a look in the cove below:
ticketsSoldTextBox.Text += totalInput;
However, this keeps concatenating the values instead of adding them.
1st run: 3; // with values of 1, 1, 1
2nd run: 36; // with values of 2, 2, 2
3rd run: 369; // with values of 3, 3, 3
The output that I'm expecting in the totalInput TextBox should be the addition of 3 + 6 + 9 which equals to 18.
Does it makes sense? I'm kinda getting frustrated with this already? Do I need to create a loop for this?

You are concatenating strings by ticketsSoldTextBox.Text += totalInput;
CastticketsSoldTextBox.Text to an integer and then add them together.
private static void Sum()
{
string input1 = "1";
string input2 = "2";
string input3 = "3";
// Int32.Parse(ticketsSoldTextBox.Text)
int sum =Int32.Parse(input1) + Int32.Parse(input2) + Int32.Parse(input3);
Console.WriteLine(sum); // print 6 in the console
}
Error handling also required to avoid Null exception error

Related

Subtraction between multiple random input numbers

i want to make user input random number example : 5-3-10-50
, system will split " - " and then the result 5 3 10 50
, how to make subtraction from first number minus second number and so on,
like this 5 - 3 = 2 , 2 - 10 = -8 , -8 - 50 = -58
and then system will print the final answer -58
my code :
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out _))
{
double NumberResult = Convert.ToDouble(result);
Answer -= NumberResult;
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}
i know my code is wrong, im beginner i already try to fix this but i cant fix it until now, i hope someone tell me what's wrong with my code and fix it too, thank you.
The reason yours doesn't work is because you set Answer = 0.
And you used foreach. On the first iteration of the loop, the first number is subtracted from Answer which results in -5.
Use for (int i=1; i<arr.Length; i++)
instead of foreach
Start from index 1, and then subtract the values.
Example:
var arr = InputNumber.Split('-');
double Answer = 0;
if (double.TryParse(arr[0], out _))
{
// We set Answer to the first number, since nothing is subtracted yet
Answer = Convert.ToDouble(arr[0]);
}
// We start index from 1, since subtraction starts from 2nd number on the String array
for (int i=1; i<arr.Length; i++)
{
if (double.TryParse(arr[i], out _))
{
double NumberResult = Convert.ToDouble(arr[i]);
Answer -= NumberResult;
}
}
Tested on Online C# Compiler
You would need a condition inside the foreach loop to check for the first parsed double before you begin subtraction. Also there is no need to call Convert.ToDouble() since the double.TryParse() function already returns the parsed double value, All you would need is a variable to contain the out value of the double.TryParse() function, See example below
bool Subtraction = true;
int AskSubtraction = 0;
while (Subtraction)
{
Console.Write("\n" + "input number ( example : 1 - 2 - 3 - 4 ) : ");
var InputNumber = Console.ReadLine();
double Answer = 0;
double numResult;
foreach (var result in InputNumber.Split('-'))
{
if (double.TryParse(result, out numResult))
{
if(Math.Abs(Answer)>0){
Answer -= numResult;
}
else{
Answer=numResult;
}
}
else
{
Console.WriteLine("\n" + "Wrong input !");
AskSubtraction++;
}
}
Console.WriteLine("\n" + "subtraction result : " + Answer);
}

can anyone help me to create ternary numbers of digits 0,1,2?

I want to create a list of number combinations which consists of only three digits (0, 1, 2). If n=1 then the result is like this {0, 1, 2} .If n=2 then result is {00, 01,02, 10, 11, 12, 20, 21, 22} . If n=3 the result will be like {000,001 etc 222}. I have tried to create this function using recursion. but i failed to create.How can I use iterations to create such list.
A recursive approach could work well here, If you are running out of memory you might be going about it the rong way or you might just have a bug.
If you want to do this by iteration you can look at the problem this way: you want all the numbers from 0 to 3^n - 1 in base 3. now you just need to convert to base 3 (and pad with 0s)
Try converting to strings, checking the (length <= n), and prepending (n - length) 0's if necessary.
[EDIT] That is, assuming you are talking about the formatting...
[EDIT v2] I am sure this is not the fastest way to do it, but you could recursively list all numbers from 0 - x and use the aforementioned string methods to iterate over the numbers an check whether any characters other than 0 - n are used.
This code will give you an idea about how to approach these problems recursively. Because of the recursive nature it will have a quite a lot of duplicates. I leave that to you to remove those.Also it prints output for all n
public void GetMaxPerm(int[] array, int k, List<int> output, int start, int end)
{
string str = GetString(output);
Console.WriteLine(str);
if (k == end)
{
return;
}
for (int i = start; i < end; i++)
{
output.Add(array[i]);
GetMaxPerm(array, k + 1, output, start , end);
output.Remove(array[i]);
GetMaxPerm(array, k + 1, output, start, end);
}
return;
}
private string GetString(List<int> output)
{
string opString = String.Empty;
foreach (var str in output)
{
opString = opString + String.Format(" {0} ", str);
}
return opString;
}
Test Code :
[TestMethod()]
public void GetMaxTest1()
{
int[] array = new[] { 0, 1, 2 };
Class obj = new Class();
List<int> output = new List<int>();
obj.GetMaxPerm(array, 0, output, 0, 3);
}
Check this Gist

How to add zero number to some nober with help of Loop?

I have problem with adding a Zero-padding with for loop... here is my code:
class Program
{
static void Main(string[] args)
{
string str = "12";
for (var i = 1; i <= 6; i++)
{
Console.WriteLine(str.PadLeft(i, '0'));
Console.ReadLine();
}
}
}
Output of this is:
12
12
012
0012
00012
000012
Why are first two values repeated?
The output that I whant to get is:
12
012
0012
00012
000012
tnx for help
From String.PadLeft(Int32, Char);
A new string that is equivalent to this instance, but right-aligned
and padded on the left with as many paddingChar characters as needed
to create a length of totalWidth. However, if totalWidth is less than
the length of this instance, the method returns a reference to the
existing instance. If totalWidth is equal to the length of this instance, the method returns a new string that is identical to this instance.
That's why when i is 1 or 2, your result will be the same as 12.
You should start your loop int i = 2 instead of int i = 1.
string str = "12";
for(var i = 2; i <= 6; i++)
{
Console.WriteLine(str.PadLeft(i, '0'));
}
Output will be;
12
012
0012
00012
000012
Here a demonstration.
By the way, Console.ReadLine() seems pointless in your case since you don't read anything in your console.
Padleft takes the string and adds zeros to the left up to the length of i.
Example:
string str = "12";
str.PadLeft(1, '0') // 12
str.PadLeft(2, '0') // 12
str.PadLeft(3, '0') // 012
str.PadLeft(4, '0') // 0012
First parameter of the PadLeft method is the total lenght of the string.Since the length of your string is 2, it only add zeros to the left when i becomes 3.
If you start i from 2 then you will get the expected result.

Aligning string inside listbox c#

I'm trying to write strings with spaces into a listbox, and keep them aligned.
Here is the code:
List<String> treeNames = new List<String>();
int counter = 1;
treeNames.Add("Input ");
treeNames.Add("Output ");
treeNames.Add("Sequence Type ");
foreach (String currentData in treeNames)
{
listBox1.Items.Add(currentData + " - " + counter.ToString());
counter+=1;
}
Here's what I hope to achieve:
Input - 1
Output - 2
Sequence Type - 3
Instead, I'm getting:
Input - 1
Output - 2
Sequence Type - 3
Any ideas how can I align them?
foreach (String currentData in treeNames)
{
listBox1.Items.Add(String.Format("{0, -20} {1, 10}", currentData, ("- " + counter.ToString())));
counter += 1;
}
You can use String.PadRight method which returns a new string that left-aligns the characters in the string by padding them with spaces on the right for a specified total length.
Let's say you have 20 character maximum length for a name:
public String stringHighscore()
{
return name + name.PadRight(20 - name.Length) + "\t\t\t" + score.ToString();
}
If your name's length is 13, this will add 7 space characters. If your name's length is 9, this will add 11 space characters. That way all your name's lengths will equal 20 at the end.

Help me to understand this c# code

this code in Beginning C# 3.0: An Introduction to Object Oriented Programming
this is a program that has the user enter a couple of sentences in a multi - line textbox and then count how many times each letter occurs in that text
private const int MAXLETTERS = 26; // Symbolic constants
private const int MAXCHARS = MAXLETTERS - 1;
private const int LETTERA = 65;
.........
private void btnCalc_Click(object sender, EventArgs e)
{
char oneLetter;
int index;
int i;
int length;
int[] count = new int[MAXLETTERS];
string input;
string buff;
length = txtInput.Text.Length;
if (length == 0) // Anything to count??
{
MessageBox.Show("You need to enter some text.", "Missing Input");
txtInput.Focus();
return;
}
input = txtInput.Text;
input = input.ToUpper();
for (i = 0; i < input.Length; i++) // Examine all letters.
{
oneLetter = input[i]; // Get a character
index = oneLetter - LETTERA; // Make into an index
if (index < 0 || index > MAXCHARS) // A letter??
continue; // Nope.
count[index]++; // Yep.
}
for (i = 0; i < MAXLETTERS; i++)
{
buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]);
lstOutput.Items.Add(buff);
}
}
I do not understand this line
count[index]++;
and this line of code
buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]);
count[index]++; means "add 1 to the value in count at index index". The ++ is specifically known as incrementing. What the code is doing is tallying the number of occurrences of a letter.
buff = string.Format("{0, 4} {1,20}[{2}]", (char)(i + LETTERA)," ",count[i]); is formatting a line of output. With string.Format, you first pass in a format specifier that works like a template or form letter. The parts between { and } specify how the additional arguments passed into string.Format are used. Let me break down the format specification:
{0, 4} The first (index 0) argument (which is the letter, in this case).
The ,4 part means that when it is output, it should occupy 4 columns
of text.
{1,20} The second (index 1) argument (which is a space in this case).
The ,20 is used to force the output to be 20 spaces instead of 1.
{2} The third (index 2) argument (which is the count, in this case).
So when string.Format runs, (char)(i + LETTERA) is used as the first argument and is plugged into the {0} portion of the format. " " is plugged into {1}, and count[i] is plugged into {2}.
count[index]++;
That's a post-increment. If you were to save the return of that it would be count[index] prior to the increment, but all it basically does is increment the value and return the value prior to the increment. As for the reason why there is a variable inside square brackets, it is referencing a value in the index of an array. In other words, if you wanted to talk about the fifth car on the street, you may consider something like StreetCars(5). Well, in C# we use square brackets and zero-indexing, so we would have something like StreetCars[4]. If you had a Car array call StreetCars you could reference the 5th Car by using the indexed value.
As for the string.Format() method, check out this article.

Categories

Resources