I am trying to number each line in a RichTextBox. I have gotten the number of lines using Lines.Length. If I start typing when it is blank that will turn to 1, but if I press backspace 2-3 times then start typing it returns 0.
(I know pointless) Here is the function that return the number of lines and you can see (my failed attempt) where I tried to compare it with the TextLength to correct the value.
private int LineCount()
{
int textLength = MainIOControl.TextLength;
int lineCount = MainIOControl.Lines.Length - 1;
return (textLength == 0 && lineCount == 0) ? 0 : lineCount;
}
This return the correct value if you just start typing, but not if you press backspace a couple times when it is empty.
Am I simple overlooking something obvious?
Try calculating it yourself instead of using the Lines property:
return MainIOControl.Text.Length - MainIOControl.Text.Replace(Environment.NewLine, string.Empty).Length;
This one may work better for your situation:
private int LineCount()
{
return MainIOControl.Text.Length - MainIOControl.Text.Replace("\n", string.Empty).Length + 1;
}
Related
The if code gives correct result but the else portion gives output: 3,2,1,0 and I expecting 6,5,4,3,2,1,0 result.
uint counter = 0;
private void getting_Next_Pic()
{
if(next == true)// Here "**next**" is boolean variable
{
counter = ++counter % 7; // Getting the next pic, Flow in Forward Direction
}
else
{
counter = counter-- % 7; // Getting the previous pic, Flow in Reverse Direction
}
}
The % operator is the remainder operator. It produces the remainder of the division of the operands (the result is negative when the left-hand operand is negative).
The decrement operator when applied to a uint value of 0 results in the positive value 4,294,967,295. The remainder of dividing that number by 7 is 3 (613,566,756 times 7 is 4,294,967,292, which is 3 less than uint.MaxValue, i.e. 4,294,967,295).
In other words, the code's doing exactly what you told it to. You can't rely on the remainder operator to handle your scenario, not when the data type you're using is unsigned.
Note that this would work:
uint counter = 0;
private void getting_Next_Pic()
{
if(next == true)// Here "**next**" is boolean variable
{
counter = (counter + 1) % 7; // Getting the next pic, Flow in Forward Direction
}
else
{
counter = (counter + 6) % 7; // Getting the previous pic, Flow in Reverse Direction
}
}
Adding 6 is the same as subtracting 1 modulus 7.
All that said, I prefer not using the remainder operator for this sort of thing. There is really no need for tricky code, or even trying to optimize performance (even assuming the remainder operator did that, which in most cases it does not). IMHO it's better to just do the actual range checking that you actually care about:
int counter = 0;
private void getting_Next_Pic()
{
counter += next ? 1 : -1;
if (counter < 0)
{
counter = 6;
}
else if (counter > 6)
{
counter = 0;
}
}
Then when you read the code, it actually says exactly what it's doing. It's easy to verify it's correct, and won't confuse you or anyone else trying to figure it out again later.
I am in my second week of C# training, so I am pretty new to programming. I have to make a program that returns the smallest integer out of a series of random integer inputs. Once the input = 0, the program should break out of the loop. I am only allowed to use while and for loops. For some reason my program breaks out of loop after the second input and it looks like it doesn't even care if there is a "0" or not. Could you please see where I went wrong? I have been busting my head off with this. Sorry if this question has already been posted by somebody else but I did not find an answer to it anywhere.
PS: The zero input should be taken into account for the comparison.
So this is what I've got so far:
class Program
{
static void Main()
{
int i = 0;
int input = Int32.Parse(Console.ReadLine());
int min = default;
while (input != 0)
{
Console.ReadLine();
if (i == 0)
{
min = input;
break;
}
if (input < min && i !=0)
{
input = Convert.ToInt32(Console.ReadLine());
min = input;
}
i++;
}
Console.WriteLine(min);
}
First of all you will want to re-read the documentation for for- and while-loops. There are several useful pages out there.. e.g. for / while.
Problem
The reason why your loop breaks is that you initialize i with 0.
int i = 0;
Inside your loop you are using the if-statment to break the loop if the condition "i is 0" is met.
if (i == 0)
{
min = input;
break;
}
The input that the user has to provide each iteration of the loop is ignored by your program as you are never storing this kind of information to any variable.
while (input != 0)
{
Console.ReadLine();
// ...
}
Possible Solution
As a beginner it is helpful to tackle tasks step by step. Try to write down each of this steps to define a simple algorithm. As there are many solutions to this problem one possible way could be:
Declare minimum value + assign max value to it
Use a while loop and loop till a specific condition is matched
Read user-input and try converting it to an integer
Check whether the value is 0 or not
4.1. If the value is 0, go to step 8
4.2. If the value is not 0, go to step 5
Check whether the value is smaller than the current minimum value
5.1. If the value is smaller, go to step 6
5.2. If the value is not smaller, go back to step 3
Set the new minimum
Go back to step 3
Break the loop
End program
A program that handles the above steps could look like:
using System;
namespace FindMinimum
{
public class Program
{
static void Main(string[] args)
{
// Declare minimum value + assign initial value
int minValue = int.MaxValue;
// Loop until something else breaks out
while (true)
{
Console.WriteLine("Please insert any number...");
// Read io and try to parse it to int
bool parseOk = int.TryParse(Console.ReadLine(), out int num);
// If the user did not provide any number, let him retry
if (!parseOk)
{
Console.WriteLine("Incorrect input. Please insert numbers only.");
continue;
}
// If the user typed in a valid number and that number is zero, break out of the loop
if (parseOk && num == 0)
{
break;
}
// If the user typed in a valid number and that number is smaller than the minimum-value, set the new minimum
if (parseOk && num < minValue)
{
minValue = num;
}
}
// Print the result to the console
Console.WriteLine($"Minimum value: {minValue}.");
// Keep console open
Console.ReadLine();
}
}
}
Try This:
int input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
int min = input;
while(true)
{
if (input == 0)
break;
if (min > input)
min = input;
Console.Write("Enter number:");
input = Int32.Parse(Console.ReadLine());
}
Console.WriteLine(min);
Console.ReadKey();
I hope it helps.
I've been working on a project where I need on a button press that this line gets executed.
if (listView1.SelectedItems[0].SubItems[3].Text == "0") //Checks to see Value
{
listView1.SelectedItems[0].SubItems[3].Text = "1";// If Value is Greater, Increase and Change ListView
questionNumberLabel.Text = listView1.SelectedItems[0].SubItems[3].Text;// Increase and Change Label
}
Now I have this repeated about 10 times with each value increasing by one. But I know that this is ugly, and dysfunctional. As well as conflates the file size. I've tried a few things. Primarily this method.
if (listView1.SelectedItems[0].SubItems[3].Text == "0")
{
for (var i = 1; i < 100;)
{
if (!Int32.TryParse(listView1.SelectedItems[0].SubItems[3].Text, out i))
{
i = 0;
}
i++;
listView1.SelectedItems[0].SubItems[3].Text = i.ToString();
Console.WriteLine(i);
}
}
But instead of just adding one, it does the 100 instances and ends. The reason this is becoming a pain in the *** is because the
listView1.SelectedItems[0].SubItems[3].Text
is just that - it's a string, not an int. That's why I parsed it and tried to run it like that. But it still isn't having the out come I want.
I've also tried this
string listViewItemToChange = listView1.SelectedItems[0].SubItems[3].Text;
Then parsing the string, to make it prettier. It worked like it did before, but still hasn't given me the outcome I want. Which to reiterate is, I'm wanting the String taken from the list view to be changed into an int, used in the for loop, add 1, then restring it and output it on my listView.
Please help :(
You say you want the text from a listview subitem converted to an int which is then used in a loop
so - first your creating your loop variable, i, then in your loop you're assigning to it potentially 3 different values 2 of which are negated by the, i++. None of it makes sense and you shouldn't be manipulating your loop variable like that (unless understand what you're doing).
if you move statements around a little..
int itemsToCheck = 10; // "Now I have this repeated about 10 times "
for (var item = 0; item < itemsToCheck; item++)
{
int i;
if (!Int32.TryParse(listView1.SelectedItems[item].SubItems[3].Text, out i))
{
i = 0;
}
i++;
listView1.SelectedItems[item].SubItems[3].Text = i.ToString();
Console.WriteLine(i);
}
Something along those lines is what you're looking for. I haven't changed what your code does with i, just added a loop count itemsToCheck and used a different loop variable so your loop variable and parsed value are not one in the same which will likely be buggy.
Maybe this give you an idea. You can start using this syntax from C# 7.0
var s = listView1.SelectedItems[0].SubItems[3].Text;
var isNumeric = int.TryParse(s, out int n);
if(isNumeric is true && n > 0){
questionNumberLabel.Text = s;
}
to shortcut more
var s = listView1.SelectedItems[0].SubItems[3].Text;
if(int.TryParse(s, out int n) && n > 0){
questionNumberLabel.Text = s;
}
I am learning my first ever programming language - which is C#.
I am making my first project in my apprenticeship which is teaching me C#. It is to produce a basic calculator.
The basic calculator takes a string input and provides a result. For example, input: "5 + 5". The answer will be 10 in a decimal format.
However, part of my validation is make the even indexes of the string array only be numbers, whilst the odd indexes of the string array can only be operators of "+", "-", "*", "/". How would I do this?
I have tried to do it here but I am struggling:
for (int index = 0; index <= calculatorInput.Length; index++)
{
if (index % 2 == 0)
{
if (Decimal.TryParse(calculatorInput[index]))
{
throw new CalculatorException("Even indexes must contain a number");
}
//check for number
}
else if (//code here)
{
throw new CalculatorException("Odd indexes must contain an operator");
//check for operator
}
}
Sorry if this question is too simple, but I would greatly appreciate the help!
My apologies for the late response. The comment from Rufus L (https://stackoverflow.com/users/2052655/rufus-l) helped to provide the solution I needed at the time.
decimal temp; if (decimal.TryParse(calculatorInput[index].ToString(), out temp)){} The TryParse method takes a string and an out parameter, which you are missing. But there are better ways to do what you want. – Rufus L Nov 1 '19 at 18:58
All answers and comments were very helpful in my development however. The calculator has been finished now though there is always room for improvement.
You can focus on operators for validation. They must always be somewhere inside the input string. Minus operator is an exception here if your calculator accepts negative numbers. But if the calculator is basic and does not support negative numbers, So the code below should be enough for operator validation:
string inputString = "10 + 10";
int index = inputString.IndexOf('+');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('*');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('/');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
index = inputString.IndexOf('-');
if ((index > -1) && ((index == 0) || (index ==inputString.Length-1)))
throw new CalculatorException("YOUR ERROR MESSAGE");
///Calculation code
To increase readability I did not create a nested if-else statement.
After this code block, you can place your calculation code. I think it is enough for a new learner.
In this article Test Run K-Means++ he use C# code and Roulette Wheel Selection to get next Centroid
there is a code that implement Roulette Wheel Selection
while (sanity < data.Length * 2)
{
cumulative += dSquared[ii] / sum;
if (cumulative >= p && used.Contains(ii) == false)
{
newMean = ii; // the chosen index
used.Add(newMean); // don't pick again
break; // WHY BREAK ?? THERE IS ANOTHER BIGGER CUMULATIVE VALUES
}
++ii; // next candidate
if (ii >= dSquared.Length)
ii = 0; // past the end
++sanity;
}
but why break when meet first true condition in here :
if (cumulative >= p && used.Contains(ii) == false)
why not looping until index 19 ???
N : 20 item
Random value = 0,817325359590969
I compare the result from the code with Excel : Result if not stop at index 16
can anyone explain to me the answer of this question ?
Because you want a weighted random sampling.
Otherwise, you would always choose the last value.