Validating multiple fields - c#

I used Visual Studio to create an application that features 3 fields where 3 numbers can be added together. Now, I need to validate all 3 fields so that negative numbers cannot be added. If a negative number is entered, each field has also to return a unique message like: "please enter a positive first number."
I figured out how to do that for one field, but how do I set it up for all 3 fields to not accept negative numbers (and display a unique message)?
Here is what I have:
{
int num = int.Parse(txtNum1.Text);
if (num <0)
{
MessageBox.Show("Please enter a positive first number");
}
else
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}
Hopefully this makes sense.

This might help you
int num = 0;
bool atLeastOneisNegative = false;
foreach (Control x in this.Controls)
{
if (x is TextBox)
{
num = 0;
num = int.Parse(((TextBox)x).Text);
if(num < 0)
{
atLeastOneisNegative = true;
MessageBox.Show("Please enter a positive first number");
}
}
}
if(!atLeastOneisNegative)
{
int num1 = int.Parse(txtNum1.Text);
int num2 = int.Parse(txtNum2.Text);
int num3 = int.Parse(txtNum3.Text);
int sum = num1 + num2 + num3;
txtResult.Text = sum.ToString();
}
Whereas the question is not stating whether you are using WPF or WinForms. But the logic might help you to achieve to iterate all your TextBoxes and see the value is Positive.

It can be easier with NumericUpDown control or handling the TextBox.Validating event, but anyway:
int i1, i2, i3;
if (!int.TryParse(txtNum1.Text, out i1) || i1 < 0) { MessageBox.Show("Please enter a positive first number" ); return; }
if (!int.TryParse(txtNum2.Text, out i2) || i2 < 0) { MessageBox.Show("Please enter a positive second number"); return; }
if (!int.TryParse(txtNum3.Text, out i3) || i3 < 0) { MessageBox.Show("Please enter a positive third number" ); return; }
int sum = i1 + i2 + i3;
txtResult.Text = sum.ToString();

Related

Making a word into a sentinel value in C#

I am currently working on a program that is a loop with a sentinel value that asks the user to enter a number or enter -99 to end the program and it runs perfectly. If I were to change that -99 to just the word "Quit" is there a certain parameter that I would have to put? For example, if I want to use a letter, I know that I could use:
char (undefined parameter) = 'A'
But how would I do this with a word? When I simply try to change the value of -99 to Quit, I receive an error as expected.
using System;
class Program {
public static void Main (string[] args) {
int sum = 0;
int counter = 0;
int max = Int32.MinValue;
int min = Int32.MaxValue;
bool keepGoing = true;
while(keepGoing) {
Console.WriteLine("Please enter a number or enter -99 to stop the program:");
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
sum += number;
if (number >= max) {
max = number;
}
if (number <= min) {
min = number;
}
}
}
double average = (double) sum / counter;
Console.WriteLine($"{counter} numbers were entered.");
Console.WriteLine("The average is:" + average);
Console.WriteLine("The sum is:" + sum);
Console.WriteLine("The maximum value is:" + max);
Console.WriteLine("The minimum value is:" + min);
}
}
It's difficult to store "Quit" in an int, so the root of your problem is that you have no separation between pulling the string from the console and converting it to an int:
int number = Convert.ToInt32(Console.ReadLine());
if (number == -99){
keepGoing = false;
} else {
counter++;
If you did have a separation, it becomes possible:
string input = Console.ReadLine();
if (input == "Quit"){
keepGoing = false;
} else {
int number = Convert.ToInt32(input);
counter++;

How do I make random numbers follow certain custom rules?

I am trying to make a random Trinomial generator and I want the 2 random numbers to follow the trinomial rules (num1+num2=b)(num1*num2=c)
string a = "x²";
int b = new Random().Next(-50, 50);
int c = new Random().Next(-50, 50);
Console.WriteLine(a,b,c);
while (true)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
if ((num1 + num2 == b) && (num1 * num2 == c))
{
Console.WriteLine("Correct.");
break;
}
else
{
Console.WriteLine("Wrong. Try again");
}
}
I expect the numbers to be written down but they aren't. Also, I don't know how to make the random numbers follow these rules. PS - The random numbers are always the same, how do I change that?
Try this:
string a = "x²";
var randomGenerator = new Random();
int b = randomGenerator.Next(-50, 50);
int c = randomGenerator.Next(-50, 50);
Console.WriteLine("{0},{1},{2}", a, b, c);
bool isRunning = true;
while (isRunning)
{
int num1 = int.Parse(Console.ReadLine());
int num2 = int.Parse(Console.ReadLine());
if ((num1 + num2 == b) && (num1 * num2 == c))
{
Console.WriteLine("Correct.");
isRunning = false;
}
else
{
Console.WriteLine("Wrong. Try again");
}
}
Console.ReadLine();
Explanation:
First of all the Random problem. Random generates numbers not really in a random way but calculates them. So since it is an algorithm it would work the same every try. To counter that, random seeds itself with the current time which then changes the output of the algorithm. In your case you create 2 random objects, but they will be generated so fast, that both actually seed with the same time, therefore calculating the same "random" numbers. That's why in my solution, we only create one Random object.
Second: If you just want to write one string to the console, jus concat the string and pass it as one parameter.
Here's my attempt at Charles' suggestion:
var rand = new Random();
string a = "x²";
int num1 = rand.Next(-50, 50);
int num2 = rand.Next(-50, 50);
int b = num1 + num2;
int c = num1 * num2;
Console.WriteLine($"{a}, {b}, {c}");
while (true)
{
int guess1 = int.Parse(Console.ReadLine());
int guess2 = int.Parse(Console.ReadLine());
if (guess1 == num1 && guess2 == num2)
{
break;
}
Console.WriteLine("Wrong. Try again");
}
Console.WriteLine("Correct.");
I've simplified the logic at the end a bit, but it should work the same.

How can I make int command in boolean instead?

I want to make the same as I did here, to do the same operation, but instead of doing the int first_dig and second_dig I want to use it with boolean, something like: bool check = (new code here);
Console.Write("Enter a two digit number: ");
int two_dig_num = int.Parse(Console.ReadLine());
if (two_dig_num >= 10 && two_dig_num <= 99)
{
int first_dig = two_dig_num % 10;
int second_dig = two_dig_num / 10;
if (first_dig == second_dig)
Console.WriteLine("YES!");
else
Console.WriteLine("NO...");
}
else
Console.WriteLine("\nYou haven't entered a Two Digit Number,\nPlease exit the program and try again later");
return;
}
}
}
first_dig == second_dig returns you bool, so if you want to store it in some variable then just:
bool value = first_dig == second_dig;
or with less variables it can be:
bool value = two_dig_num % 10 == two_dig_num / 10;
That is it.

Sum integers using a loop c#

I am new to programming and I think I have confused myself I'm trying to make a loop that asks users for integers when the user inputs a integer greater than 100 then the console displays the amount of integers the user has input and the sum of these integers. I know it's basic but I can't figure where I went wrong.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum1, strNum2;
int num1, num2;
int i = 0;
int sum =0 ;
Console.WriteLine("Please enter a integer between 1 and 100"); // asks for user input
strNum1 = Console.ReadLine();
num1 = int.Parse(strNum1);
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum2 = Console.ReadLine();
num2 = int.Parse(strNum2); //input is stored as num2
sum = num2; //store num2 in sum
i++;
if (num2 >= 100) // if num2 int is greater than 100
{
sum = (num1 +num2 +sum); // do calculation
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
while (i < 100);
}
}
}
any help would be appreciated thanks everyone!
You're on the right track... a couple of things:
Do... While is used when you always want to run through the block at least once, so your first 'get' from the user can be inside the block. You can code whatever you want to happen after the condition fails right after the block, instead of checking the same condition inside it.
Make sure if you're simply using Parse that you wrap it in a try...catch, because your user could type in anything (not just numbers). Personally I usually use TryParse instead.
Finally, make sure you're comparing to the correct variable. Checking that i < 100 will keep looping until 100 numbers have been entered; you want to compare the user's input instead.
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string prompt = "Please enter {0} integer between 1 and 100";
string strNum;
int num = 0;
int i = 0;
int sum =0 ;
do //ask once and repeat while 'while' condition is true
{
string pluralPrompt = i > 0 ? "another" : "an";
prompt = string.Format(prompt,pluralPrompt);
Console.WriteLine(prompt); // asks for user input
strNum = Console.ReadLine();
if (!Int32.TryParse(strNum, out num)) //input is stored as num
{
// warn the user, throw an exception, etc.
}
sum += num; //add num to sum
i++;
}
while (num < 100);
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
}
}
}
namespace Wip
{
class Program
{
static void Main(string[] args)
{
string strNum;
int num;
int i = 0;
int sum = 0;
do //repeat asking for user input
{
Console.WriteLine("Please enter another integer between 1 and 100"); // asks for user input
strNum = Console.ReadLine();
if (int.TryParse(strNum, out num)) //input is stored as num2
{
if (num < 101)
{
i++;
sum += num;
continue;
}
else
{
Console.WriteLine("No of integers entered is {0} {1}", i, sum); //output calculation
break;
}
}
}
while (i < 100);
}
}

How can I get this code to loop correctly?

int a = 0;
int b = 0;
for (int c = 0; c < 2; c++)
{
Console.WriteLine("Give me a number");
int h = Convert.ToInt16(Console.ReadLine());
switch (c)
{
case 0:
a = h;
while (a <100 || a>250)
{
Console.WriteLine("That number is too large");
break;
}
break;
case 1:
b = h;
while (a < 100 || a > 250)
{
Console.WriteLine("That number is too large");
break;
}
break;
}
}
Console.WriteLine("{0}",a+b);
Console.ReadKey();
When I input numbers greater than 250 or less than 100 it does give me the message ("That number is too large") but the problem is that it still executes the addition at the end of the code. I am trying to make it so that if those numbers fall outside of that range, it asks me again for the numbers. Any tips on how I can do this?
Subroutines are wonderful things, and useful in many situations.
int GetNumberBetween( int minValue, int maxValue )
{
int h;
for (;;)
{
Console.WriteLine("Give me a number");
h = Convert.ToInt32(Console.ReadLine());
if ( h >= minValue && h <= maxValue )
break;
Console.WriteLine("I don't like that number, try again");
}
return( h );
}
void DisplaySum( void )
{
int a = GetNumberBetween( 100, 250 );
int b = GetNumberBetween( 100, 250 );
Console.WriteLine("{0}",a+b);
Console.ReadKey();
}
You need a better control on your external loop. Instead of a for use a while and increment the variable C only when you have a good number.
int a = 0;
int b = 0;
int c = 0;
while (c < 2)
{
Console.WriteLine("Give me a number");
int h;
if(!Int32.TryParse(Console.ReadLine(), out h)
{
Console.WriteLine("Not a valid number");
continue;
}
switch (c)
{
case 0:
a = h;
if(a <100 || a>250)
Console.WriteLine("That number is too large");
else
c = 1;
break;
case 1:
b = h;
if(b < 100 || b > 250)
Console.WriteLine("That number is too large");
else
c = 2;
break;
}
}
Console.WriteLine("{0}",a+b);
Console.ReadKey();
By the way, I suggest to use Int32.TryParse instead of Convert.ToInt32 (What happen in your code if the user types something that cannot be converted to a number?)
I have also fixed a typo in your second test. You should use the variable b instead of a
You're over thinking the solution. If you are just trying to sum two numbers, then simply do that. Think of it logically. You can add the error messages as needed.
Get the number for a
Get the number for b
Sum the numbers
Note: If you need to sum more than two numbers then this solution won't work
//...
int a = 0;
//Capture a value for a, and range check it
while (a < 10 || a > 50)
{
Console.WriteLine("Give me a number for (a)");
a = Convert.ToInt32(Console.ReadLine());
}
int b = 0;
//Capture a value for b, and range check it
while (b < 10 || b > 50)
{
Console.WriteLine("Give me a number for (b)");
b = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine("{0}", a + b);
Console.ReadKey();
//...
EDIT:
int a = 0;
//Get a value for a
while (true)
{
Console.WriteLine("Give me a number for (a)");
a = Convert.ToInt32(Console.ReadLine());
//Range check and exit if valid
if (a >= 10 && a <= 50)
break;
Console.WriteLine("That number is too large");
}
int b = 0;
//Get a value for b
while (true)
{
Console.WriteLine("Give me a number for (b)");
b = Convert.ToInt32(Console.ReadLine());
//Range check and exit if valid
if (b >= 10 && b <= 50)
break;
Console.WriteLine("That number is too large");
}
Console.WriteLine("{0}", a + b);
Console.ReadKey();

Categories

Resources