I currently have this, but it keeps resulting in the number say I put in 5 it will make it 51 instead of the result I want of 6. Can anyone help me?
int number;
int outcome;
number = int.Parse(numberInputTextBox.Text);
outcomeLabel.Text = number + 1 .ToString();
number = int.Parse(numberInputTextBox.Text);
outcomeLabel.Text = (number + 1).ToString();
You forgot to add ( ). Your sample was:
1) take 1 and convert to string
2) add number and string
in point 2) the number was casted to string before adding to second string. That's why you got string concatenation "5"+"1"="51" instead of integer sum 5+1=6
1.ToString() will return a string, which you are then adding the string "5" to, as C# will
implicitly cast the number 5 to the string "5" when trying to add it to a string.
You need to first add one, then convert to a string, giving something like this:
outcomeLabel.Text = (number + 1).ToString();
or
int newNumber = number + 1;
outcomeLabel.Text = newNumber.ToString();
Just add parentheses...
number = int.Parse(numberInputTextBox.Text);
outcomeLabel.Text = (number + 1).ToString();
Related
I have the following problem here:My input is several lines of 2 digit numbers and I need to make a new number using the second digit of the first number and the first of the next one.
Example:
int linesOfNumbers = Convert.ToInt32(Console.ReadLine());
for(int i = 0,i<linesOfNumbers,i++)
{
int numbers = Conver.ToInt32(Console.ReadLine());
//that's for reading the input
}
I know how to separate the numbers into digits.My question is how to merge them.
For example if your input is 12 and 21 the output should be 22.
I like oRole's answer, but I think they're missing a couple things with the example input that you provided in your comment. I'll also point out some of the errors in the code that you have.
First off, if you're only given the input 12,23,34,45, then you don't need to call Console.ReadLine within your for loop. You've already gotten the input, you don't need to get any more (from what you've described).
Secondly, unless you're doing mathematical operations, there is no need to store numerical data as ints, keep it as a string, especially in this case. (What I mean is that you don't store Zip Codes in a database as a number, you store it as a string.)
Now, onto the code. You had the right way to get your data:
var listOfNumbers = Console.ReadLine();
At that point, listOfNumbers is equal to "12,23,34,45". If you iterate on that variable as a string, you'll be taking each individual character, including the commas. To get each of the numbers to operate on, you'll need to use string.Split.
var numbers = listOfNumbers.Split(',');
This turns that list into four different two character numbers (in string form). Now, you can iterate over them, but you don't need to worry about converting them to numbers as you're operating on the characters in each string. Also, you'll need a results collection to put everything into.
var results = new List<string>();
// Instead of the regular "i < numbers.Length", we want to skip the last.
for (var i = 0; i < numbers.Length - 1; i++)
{
var first = numbers[i];
var second = numbers[i + 1]; // This is why we skip the last.
results.Add(first[1] + second[0]);
}
Now your results is a collection of the numbers "22", "33", and "44". To get those back into a single string, you can use the helper method string.Join.
Console.WriteLine(string.Join(",", results));
You could use the string-method .Substring(..) to achieve what you want.
If you want to keep int-conversion in combination with user input, you could do:
int numA = 23;
int numB = 34;
int resultAB = Convert.ToInt16(numA.ToString().Substring(1, 1) + numB.ToString().Substring(0, 1));
Another option would be to take the users input as string values and to convert them afterwards like that:
string numC = "12";
string numD = "21";
int resultCD = Convert.ToInt16(numC.Substring(1, 1) + numD.Substring(0, 1));
I hope this code snippet will help you combining your numbers. The modulo operator (%) means: 53 / 10 = 5 Rest 3
This example shows the computation of the numbers 34 and 12
int firstNumber = 34 - (34 % 10) // firstNumber = 30
int secondNumber = 12 % 10; // secondNumber = 2
int combined = firstNumber + secondNumber; // combined = 32
EDIT (added reading and ouput code):
boolean reading = true;
List<int> numbers = new ArrayList();
while(reading)
{
try
{
int number = Convert.ToInt32(Console.ReadLine());
if (number > 9 && number < 100) numbers.Add(number);
else reading = false; // leave reading process if no 2-digit-number
}
catch (Exception ex)
{
// leave reading process by typing a character instead of a number;
reading = false;
}
}
if (numbers.Count() > 1)
{
List<int> combined = new ArrayList();
for (int i = 1; i <= numbers.Count(); i++)
{
combined.Add((numbers[i-1] % 10) + (numbers[i] - (numbers[i] % 10)));
}
//Logging output:
foreach (int combination in combined) Console.WriteLine(combination);
}
As you mention, if you already have both numbers, and they are always valid two digit integers, following code should work for you.
var num1 = 12;
var num2 = 22;
var result = (num2 / 10)*10 + (num1 % 10);
num2/10 returns the first digit of second number, and num1 % 10 returns the second digit of the first number.
The % and / signs are your savior.
If you want the 'ones' digit of a number (lets call it X), simply do X%10 - the remainder will be whatever number is in the 'ones' digit. (23%10=3)
If, instead, the number is two digits and you want the 'tens' digit, divide it by ten. (19/10=1).
To merge them, multiply the number you want to be in the 'tens' digit by ten, and add the other number to it (2*10+2=22)
There are other solutions like substring, etc and many one have already given it above. I am giving the solution VIA LINQ, note that this isn't efficient and it's recommended only for learning purpose here
int numA = 12;
int numB = 21 ;
string secondPartofNumA = numA.ToString().Select(q => new string(q,1)).ToArray()[1]; // first digit
string firstPartofNumB = numB.ToString().Select(q => new string(q,1)).ToArray()[0]; // second digit
string resultAsString = secondPartofNumA + firstPartofNumB;
int resultAsInt = Convert.ToInt32(resultAsString);
Console.WriteLine(resultAsString);
Console.WriteLine(resultAsInt);
I have next 'while' statement which I should re-write on VB:
while (--number >= 0)
{
result = (char)('A' + number % lettersNumbers) + result;
number /= lettersNumbers;
}
I've tried something like this:
While number >= 0
number = number - 1
result = Chr(Chr("A") + number Mod lettersNumbers) & result
number = number / lettersNumbers
WEnd
But unfortunately it doesn't works. I am getting next error:
Type mismatch: '[string: "A"]'
So how to correct this code to make it work on VBscript?
You need to get the character code of "A":
While number >= 0
number = number - 1
result = Chr(Asc("A") + number Mod lettersNumbers) & result
number = number / lettersNumbers
WEnd
The function Asc returns the Ascii code for a given letter. in your original you use a charcater (char) in a calculation. C# implicitly converts char to int.
While number >= 0
number = number - 1
result = Chr(Asc("A") + number Mod lettersNumbers) & result
number = number / lettersNumbers
WEnd
You need to get the character code of "A":
protected void btnView_Click(object sender, EventArgs e)
{
int StudentAdmissionNo = Convert.ToInt32(txtAdmissionNo.Text);
string StudentName = txtStudentName.Text;
DateTime DateOfBirth = Convert.ToDateTime(txtDOB.Text);
string Gender = txtGender.Text;
string Standard = txtstandard.Text;
string Section = txtSection.Text;
int Telugu = Convert.ToInt32(txtTelugu.Text);
int English = Convert.ToInt32(txtEnglish.Text);
int Mathematics = Convert.ToInt32(txtMathematics.Text);
//int Total = Convert.ToInt32(lblTot.Text);
//double Average = Convert.ToDouble(lblAve.Text);
string Result = lblRes.Text;
lblTot.Text = (txtTelugu.Text + txtEnglish.Text + txtMathematics.Text); # Total in coming if i enter the 45 65 65 = its coming 456565 like i did wrong?
lblAve.Text = ((lblTot.Text) / 3.00); //This also gives an error
}
In this code I have an error coming from lblTot = to add marks and it coming like same to printing that numbers what I entered and average also not working.
You are concatenating the Text. When you use + with text/string it acts as a concatenation operator.
You need to convert text to Integer for arithmatic operations first.
Use Convert.ToInt32(input);
Replacing your code with the below lines should fix it.
lblTot.Text = (Convert.ToInt32(txtTelugu.Text) + Convert.ToInt32(txtEnglish.Text) + Convert.ToInt32(txtMathematics.Text)).ToString();
lblAve.Text = ((Convert.ToInt32(lblTot.Text)) / 3.00).ToString();
Update
I just noticed that you have already assigned the required values to integers here:
int Telugu = Convert.ToInt32(txtTelugu.Text);
int English = Convert.ToInt32(txtEnglish.Text);
int Mathematics = Convert.ToInt32(txtMathematics.Text);
Which is correct, you just needed to add these variables, like:
int total = Telugu + English + Mathematics;
lblTot.Text = total.ToString();
And then, for average just use the total variable that we just assigned the value to:
lblAve.Text = Convert.ToString(Convert.ToDouble(total / 3.00)); // convert the average to double as you may get values with decimal point. And then convert it back to string in order to assign it to a Label control.
If my assumption of what you're trying to do is correct your code should look like this.
decimal total = Teluga + English + Mathematics;
decimal average = (Teluga + English + Mathematics) / 3.00;
lblTot.Text = total.ToString();
lblAve.Text = average.ToString();
You are trying to use strings to perform mathematical operations and that won't work.
Also, typically
int x = Int32.TryParse(txtEnglish.Text)
is a better way to turn string into integers
The root of both your problems is that a textbox.Text property is a string.
In your first problem, you are concatenating strings, which is why it's giving you you 456565.
In your second problem, you are trying to perform arithmetic on a string and a number.
Cast your strings as numbers by declaring an Int32 variable placeholder and using the TryParse method on your string, like so:
Int32 txtTeluguResult;
Int32.TryParse(txtTelugu.Text, txtTeluguResult);
Also note that TryParse will put 0 in for your result variable if it cannot successfully parse the text input. You may wish to use Convert.ToInt32() instead, which throws a FormatException if it fails, depending on what behavior you want.
lblTot.Text = (txtTelugu.Text + txtEnglish.Text + txtMathematics.Text); # Total in coming if i enter the 45 65 65 = its coming 456565 like i did wrong?
lblAve.Text = ((lblTot.Text) / 3.00); this also giving error?
you are using string variables not int or real or decimal
do something like
lblTot.Text = (((int)txtTelugu.Text + (int)txtEnglish.Text + (int)txtMathematics.Text)).ToString();
lblAve.Text = (((int)(lblTot.Text) / 3.00)).ToString(); this also giving error?
How to find a loop that will successfully add 5 numbers. Here is the homework question.
Add a loop that will take a number input by the user and add it to a running total (the ReadLine() method will get a string from the user).
You’ll notice in the above code there are two variables declared.
One is total of the double data type which will have the total of the 5 entered numbers.
The other is a temp string variable to take the user input, convert to double, and then add the converted value to the total.
Using what you have learned in case 2 about taking input and converting to an int32, take the input and convert ToDouble() instead of int32.
total = total + Convert.ToDouble(temp);
case "3":
double total = 0;
string temp = "0";
Console.WriteLine("Enter 5 numbers here for addition \n");
for (total = 0; total <= 6; total++);
{
Console.WriteLine(total + "" + temp);
total = total + Convert.ToDouble(temp);
}
break;
When I tried entering this in, the debugging program exited out and gave me a set number.
It keeps saying that string will not convert to integer when I tried entering string as an expressions instead.
Here is the result I am trying to get.
1
2
3
4
5
Total:15 This is the answer I am trying to get.
You set temp to be an empty string and then it never becomes a number, hence you can't cast it to a double....
Convert.ToDouble(input) won't do anything either as you need to store the value, i.e.
double result = Convert.ToDouble (input)
The loop is wrong because you only ever take one input - you need to put your Console.ReadLine in your loop and then append what the user inputs to your total.
you probably need to do:
int index=Convert.ToDouble(input);
and use in the for loop something like
for(int i=0;i<index;i++)
since as it stands you retrieve an input but don't use it, in for loop in fact you're trying to set it to zero -> for(input=0;....)
which can't be done since input is a string and not a number
in case 3 you're using total as an index and as the total variable in the calculation you can't do that
you need another variable to use as a index:
for (int i = 0; i<= 6; i++);
{
Console.WriteLine(total + "" + temp);
total = total + Convert.ToDouble(temp);
}
Console.Write("Enter how many numbers you want to enter and sum up: ");
double n = double.Parse(Console.ReadLine());
double r;
double sum = 0;
for (int i = 0; i < n; i++)
{
Console.Write("{0} Enter number ", i);
r = double.Parse(Console.ReadLine());
sum += r;
Console.WriteLine(sum);
}
Well, I've tried it with ToInt, ToString, and I'm out of options.
I'm trying to substract 2 Label Texts from each other. (Those contains numbers from RSS)
What I have at the moment:
lblOldID.Text = nodeChannel["oldid"].InnerText;
lblNewID.Text = nodeChannel["newid"].InnerText;
So let's say oldid contains "500" and newid "530".
But for some reason, I can't substract (-) them.
What I want:
lblResultID.Text = lblOldID.Text - lblNewID.Text;
Example: Result = 530 - 500
So how is that possible?
You need to convert the text to ints.
//These are the ints we are going to perform the calculation on
Int32 oldID = 0;
Int32 newID = 0;
//TryParse returns a bool if the string was converted to an int successfully
bool first = Int32.TryParse(lblOldID.Text, out oldID);
bool second = Int32.TryParse(lblNewID.Text, out newID);
//Check both were converted successfully and perform the calculation
if(first == true && second == true)
{
lblResultID.Text = (oldID - newID).ToString();
}
else
{
lblResultID.Text = "Could not convert to integers";
}
TryParse prevents an exception being thrown if the data in the labels cannot be converted to integers. Instead, it returns false (or true if the numbers were parsed successfully).
If you want the label text to be, literally, 530 - 500, concatenate the strings like so:
lblResultID.Text = lblOldID.Text + " - " + lblNewID.Text;
If you want the label text to be the result of subtracting the numbers represented in the labels, convert them to integers first:
int old = Int32.Parse(lblOldID.Text);
int new = Int32.Parse(lblNewID.Text);
lblResultID.Text = (old - new).ToString();
(You'll need some error checking in there if there's the possibility that either value might not convert cleanly to an integer)
Perhaps because you really should parse them:
lblResultID.Text = (int.Parse(lblOldID.Text) - int.Parse(lblNewID.Text)).ToString();
Or in string format:
lblResultID.Text = lblOldID.Text + " - "+ lblNewID.Text;