This is essentially what I am trying to do. I want to allow someone to enter a number on how many times they want to run a specific program. What I can't figure out is how to change the number 10 into (textBox1.Text). If you have a better way please let me know. I am very new to programming.
int counter = 1;
while ( counter <= 10 )
{
Process.Start("notepad.exe");
counter = counter + 1;
}
This shows how to take the user-supplied input and safely convert it to an integer (System.Int32) and use it in your counter.
int counter = 1;
int UserSuppliedNumber = 0;
// use Int32.TryParse, assuming the user may enter a non-integer value in the textbox.
// Never trust user input.
if(System.Int32.TryParse(TextBox1.Text, out UserSuppliedNumber)
{
while ( counter <= UserSuppliedNumber)
{
Process.Start("notepad.exe");
counter = counter + 1; // Could also be written as counter++ or counter += 1 to shorten the code
}
}
else
{
MessageBox.Show("Invalid number entered. Please enter a valid integer (whole number).");
}
textBox1.Text will return a string. You need to convert it into an int and since it's taking user input, you'll want to do so safely:
int max;
Int32.TryParse(value, out max);
if (max)
{
while ( counter <= max ) {}
}
else
{
//Error
}
Try System.Int32.TryParse(textBox1.Text, out counterMax) (Docs on MSDN) to convert a string to a number.
This will return a true if the conversion succeeded or a false if it failed (i.e., the user entered something that isn't an integer)
I would suggest to use MaskedTextBox control to take input from user, which will help us to ensure that only numbers will supplied. It will not bound us for TryParse functionality.
Set mask like this: (can use "Property Window")
MaskedTextBox1.Mask = "00000"; // will support upto 5 digit numbers
then use like this:
int finalRange = int.Parse(MaskedTextBox1.Text);
int counter = 1;
while ( counter <= finalRange )
{
Process.Start("notepad.exe");
counter = counter + 1;
}
use Try Catch body ,like this function
bool ErrorTextBox(Control C)
{
try
{
Convert.ToInt32(C.Text);
return true;
}
catch { return false; }
}
and use
Related
I have a fixed int value - 1050. I have around 50 dynamic values that I want to compare with the fixed value. So I compare it in a for loop. I have a public variable which I set as ok or notok depending on result. But my problem is that the value of the public variable is always the last value that I compared. Example, If I have the 20th dynamic value as 1000, it should return notok, but the value of the variable is always the last compared value. How do I set the variable to notok even if one/multiple of the values of dynamic variable doesnt match with fixed variable? I also display the total number of notok values in a listbox.
Here is what I have:
string result;
for(int i = 0; i < dynamicvalue.count; i++)
{
if(dynamicvalue[i] != setvalue)
{
result = "notok";
listBox1.Items.Add(result);
}
else
{
result = "ok";
}
}
To have "notok" if theres at least one not matching, one way to do it in plain code:
string result = "ok";
for(int i=0; i<dynamicvalue.count; ++i)
{
if(dynamicvalue[i] != setvalue)
{
result = "notok";
break;
}
}
You can use .Any() from Linq,
Determines whether any element of a sequence exists or satisfies a
condition.
string result = dynamicvalue.Any(x => x == setValue) ? "Ok" : "Not Ok";
If you want to use for loop without a break statement, you are just increasing the time complexity of your code.
I will never recommend it, but if you want you can try the below code
string result = "Ok";
bool flag = true;
//This for loop will iterate for n times.
for(int i = 0; i < dynamicvalue.Count; i++)
{
if(dynamicvalue[i] != setvalue && flag)
{
result = "Not Ok";
flag = false; //flag will help us to execute this block of code only once.
}
}
Perhaps the most performant way to answer this would be to keep your numbers in a HashSet instead (make dynamicvalue a HashSet<int>), then it's:
dynamicvalue.Contains(setvalue) ? "ok" : "notok"
A HashSet can much more quickly answer "do you contain this value?" than a list/array can
By the discussion going on in the comments I'm thinking that you want to go through all the elements in dynamicvalue and check all if any of them are ok or notok. If that is the case, you should turn result into an array. You get the last compared result because each time the cycle loops, the string gets assigned a new value all over again so the previous value gets discarded.
Is this what you want to do? I wrote it in c++
int setvalue = 1050;
int notok = 0;
int dynamicvalue[5] = {1, 2, 3, 1050, 4}; //for example
string result[5];
for (int i = 0; i < sizeof(dynamicvalue); i++){
if (dynamicvalue[i] != setvalue){
result[i] = "notok";
notok++; //to keep track of notok
}
else{
result[i] = "ok";
}
}
Afterwards if you cycle through the result array you will see that all the values were saved. I find it simpler to have an int variable to know how many times the result was notok
You forgot to get the actual value within dynamicvalue: your test should be if (dynamicvalue[i] != setvalue).
EDIT: And add a break; after the result="ok"; instruction to break the loop, too.
EDIT 2: An above answer gives the corrected code using a break.
I found a solution to this by reading #deminalla 's answer.
I added two more integers to work as counters and after the for loop I compare the values of these integers to get the final result.
Here's what I did:
string result;
int okcounter = 0;
int notokcounter = 0;
for(int i = 0; i < dynamicvalue.count; i++)
{
if(dynamicvalue[i] != setvalue)
{
notokcounter ++;
listBox1.Items.Add(notokcounter);
}
else
{
okcounter++;;
}
}
if(notokcounter >=1)
{
result = "notok";
}
else if(okcounter == dynamicvalue.count)
{
result = "ok";
}
I want to generally verify if a number/character exists within a specified index of an int value.
Here is pseudocode of what I want
if (octet[1].Exists){
return true;
} else {
return false;
}
// receiving int octet = 103 will return true.
// receiving int octet = 7 will return false.
Is there a function that already does this, or do you have to make one on your own?
Convert to a string then check the length?
var str = octet.ToString();
return str.Length >= 1;
I don't know a function like this, but you can write your own.
In instance:
var func = (int octet, int index) => (octet / (int)(Math.Pow(10, index)) != 0);
I would suggest using a System.Linq binding for this. Here is an example:
octet.ToString().Contains(n);
Where n is the digit you're looking for in string or char form. Hope this helps!
Just parse the int to a string and check if the number you are looking is equal to expected position.
var number = 12345;
if(number.ToString().IndexOf('2') == 1)//check if the value 2 is on the second position of the array
{
Console.WriteLine("yes");
}
ok I am running into a problem. I have a decimal in a textbox that I am trying to Range between a set number. As you can see in the picture I have a value that is in the Full Scale, which updates the value on the CalCert with the decimal 2.9995 mV/V.
The issue here is the decimal value has to be plus/minus 30 of 3 mV. example. 2.9970 - 3.0030 that is the range. Anything outside the range I am needing it to trigger a warning dialog. My code that I was going to use I am not sure why its not working.
I am using if statements but the only error is in the ("3.0031") section.
double value = 0;
if (double.TryParse(TxtFullScale.Text, out value))
{
value /= 10000;
}
TxtCalFullScale.Text = string.Format("{0:#.0000}", value) + " " + "mV/V";
if (TxtFullScale.Text >= TxtFullScale.Text.ToString("3.0031"))
{
MessageBox.Show("Full Scale value is in a non conformence state.");
}
else if (TxtFullScale.Text <= TxtFullScale.Text.ToString("2.9970"))
{
MessageBox.Show("Full Scale value is in a non conformence state.");
}
I can take and make the code work with to a point with
if (TxtFullScale.Text == "3.0031")
{
MessageBox.Show("Full Scale value is in a non conformence state.");
}
else if (TxtFullScale.Text =="2.9970")
{
MessageBox.Show("Full Scale value is in a non conformence state.");
}
However if the range is put in the text as 3.0032 then it never shows the messagebox. What am I missing here?
So, first, you can't do math operations with strings on C#
var a = "3";
var b = "2";
Console.WriteLine(a+b);
Will result in 32!
Second, this line is a bit strange
TxtFullScale.Text >= TxtFullScale.Text.ToString("3.0031")
Should be like
TxtFullScale.Text >= "3.0031"
you need to parse the number as an decimal, then compare, like this:
public const double LIMIT_1 = 3.0031;
public static void Main()
{
var val = "3.0032";
var x = double.TryParse(val, out double dec);
if(dec >= LIMIT_1)
Console.WriteLine("yay");
}
I'm new to C# and i would really need your help with a project.
The idea is to ask the user for 10 numbers between 1-20. The numbers that the user enters are stored in an array. In the next phase a random number i generated and then the program compare all the numbers that the user previously entered with the random number. If one of numbers matches the program write something like "You win!".
My current solution is okay and working but I want a better exception handling than the current one. Here is my problem:
As you can see in my code below I rely on a loop and try/catch to ensure that the user enters a valid number, but after testing several times I discovered that if you enter a valid input, let say the first time but not the second, the unvalid input is still sent to the for-loop and to the next index.
I want to ensure that the user enters a valid number and if not the for-loop would temporarily "pause" until the next VALID number is entered.
bool start = true; //Create a loop.
{
while (start == true)
{
try
{
for (int x = 0; x < vektor.Length; x++) //To fill my array.
{
Console.WriteLine("Enter a number between 1 and 20:");
vektor[x] = int.Parse(Console.ReadLine());
start = false;
}
}
catch
{
Console.WriteLine("Error, you need to enter a number!");
}
}
}
Make a method that asks the user a question and doesn't give an answer until it's valid:
public int Ask(string question, int lower, int upper){
while(true)
{
Console.WriteLine(question);
string input = Console.ReadLine();
bool valid = int.TryParse(input, out int inputInt); //valid is true if it was a number
valid = valid && inputInt >= lower && inputInt <= upper; //but also test was it in range?
if(valid)
return inputInt; //if not valid, repeat the question because the loop is infinite
}
}
valid will be true if the user enters a number, but if they entered 40 for a 1 to 20 range, then the second validity assessment is:
valid = true /*it was a number*/ && true /*40 is >= 1*/ && false /*40 is not <= 20*/
So valid becomes false. We can only escape the Ask() method, returning the valid number if valid is true, otherwise the loop goes round again
--
Now you can have a list of numbers, say you want 10, we can loop and add numbers to a list until we get 10:
List<int> numbers = new List<int>();
while(numbers.Count < 10)
{
int validNumber = Ask("Enter a nubmer between 1 and 20: ", 1, 20);
numbers.Add(validNumber);
}
You can do this as an array if you like:
int[] numbers = new int[10];
for(int x = 0; x<numbers.length; x++)
{
int validNumber = Ask("Enter a nubmer between 1 and 20: ", 1, 20);
numbers[x] = validNumber;
}
Because you know that the Ask method will never return unless the input is valid, so the loop "pauses"
Okay, lets assume we have a variable with an array like this
int[] digit;
int x = 5;
for(int i=0;i < = 5; i++)
{ digit[i] = 0;}
All value array on var Digit have 0. So what i want to do its i want to increment the value on that digit from right using Button Control that adds increment (that means digit[4] to digit[3] and so on) and when the value hits certain number example 5 in digit[4], it would come back to value 0 and the next var digit incremented (digit[3]). And the incremented start again and so on.
I already try using if and switch to make this happen like this
private btnClick_Click(Object Sender, Event Args)
{
digit[4] +=1;
if(digit[4] > 5) { digit[3] += 1;}
if(digit[3] > 5) { digit[2] += 1;}
//and so on
switch(digit[4])
{
case 5: digit[4]=0;
}
//and so on
}
But its only for logic If We Know The Array Number Location. Say if i retrieve that number for somewhere like 15 digit. If we set array number so little on that command Button, it cannot fill the array right?
Imma already confused thinking this, any suggestion, help, discussion ill appreciate it. Thanks.
If you just want to increment by one, and not any substraction or increment by let's say 5, I'd use a simple solution like this:
private void btnClick_Click(Object Sender, Event Args) {
int maxValue = 5;
int carry = 1; // This is our increment
// iterate through your digits back to front
for(int i = digit.Length - 1; i >= 0; i--) {
digit[i] += carry; // increase the value by the carry. This will at least increment the last digit by one
carry = 0;
// if we reach our max value, we set the carry to one to add it to the next digit, and reset our current digit to 0.
// If you wanted to increase by more than 1 a time, we would have to add some more calculations here as it would
// be incorrect to just reset digit[i] to 0.
if(digit[i] >= maxValue) {
carry = 1; // the next digit will now be told to increase by one - and so forth
digit[i] = 0;
} else {
break; // This will break out of the for - loop and stop processing digits as everything just fit nicely and we don't have to update more previous digits
}
}
}
Not that once you reach 44444 and increment, you will end up with 00000.