while adding two number if user enter string how to restrict him - c#

Here i'm writing a simple c#program Addding two number but if user Enter string sting value how to say him Enter only integer value
int x;
int y;
int result;
string Res2;
Console.Write("\n Enter the first number to be added: ");
x = Convert.ToInt32(Console.ReadLine());
Console.Write("\n Enter the second number to be added: ");
y = Convert.ToInt32(Console.ReadLine());
if (x != null && y != null)
{
result = x + y;
Console.Write("\n The sum of two numbers is: " + result);
}

you could put something like
int x;
Console.Write("\n Enter the first number to be added: ");
while(!int.TryParse(Console.ReadLine(),out x))
{
Console.Write("\nPlease, enter a valid number: ");
}

Try below if you want to continue the program after invalid inputs
string x,y;
int a,b;
int result;
bool flag = false;
do{
if(flag)
Console.Write("\n Please enter integer values");
Console.Write("\n Enter the first number to be added: ");
x = Console.ReadLine();
Console.Write("\n Enter the second number to be added: ");
y = Console.ReadLine();
flag = true;
}
while(!int.TryParse(x, out a) || !int.TryParse(y, out b));
if (x != null && y != null)
{
result = a + b;
Console.Write("\n The sum of two numbers is: " + result);
}

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++;

Sum up all numbers between two numbers

I am a beginner in C# programming and trying to code a method that ask the user to give a start and an end integer number, then sum up all numbers from the start to the end and in case the given start number is greater than the end number, swap the values so that the start number becomes the end number and the end number gets the value of the start number.
This what I have done so far but I'm not getting the right answer when running the app:
private void SumNumbers()
{
int startNumber, endNumber;
Console.WriteLine("\nplease enter a start number: ");
startNumber = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("\nplease enter an end number: ");
endNumber = Convert.ToInt32(Console.ReadLine());
int result = 0;
for (int i=0; i<=startNumber; i=i+1)
{
result = result + i;
Console.WriteLine(i);
}
Console.ReadLine();
Console.WriteLine("The sum of Numbers between " + startNumber + " and " + endNumber + " is: " + result.ToString());
Console.ReadLine();
}
I'm getting this result: The sum of Numbers between 12 and 23 is: 78 when the result actually need to 210.
for (int i=0;i<=startNumber;i=i+1)
You are iterating from 0 to startNumber, when really you want to iterate like startNumber to endNumber.
Try
for (int i = startNumber; i <= endNumber; i = i+1)
Below is the working example.
I also added some logic to handle the checking of the input (whether it is correct or no) so the application doesn't break. This way the user experience is much better.
Here is the live working example: code
private void SumNumbers()
{
int startNumber, endNumber;
Console.WriteLine("\nplease enter a start number: ");
do
{
var input1 = Console.ReadLine();
if (Regex.IsMatch(input1, #"^\d+$"))
{
startNumber = Convert.ToInt32(input1); break;
}
else
{
Console.WriteLine("Input provided is invalid. Please enter a correct number: ");
}
} while (true);
Console.WriteLine("\nplease enter an end number: ");
do
{
var input2 = Console.ReadLine();
if (Regex.IsMatch(input2, #"^\d+$"))
{
endNumber = Convert.ToInt32(input2); break;
}
else
{
Console.WriteLine("Input provided is invalid. Please enter a correct number: ");
}
} while (true);
int min = Math.Min(startNumber, endNumber);
int max = Math.Max(startNumber, endNumber);
int result = 0;
for (int i = min; i <= max; i++)
{
result = result + i;
Console.WriteLine(i);
}
Console.WriteLine("The sum of Numbers between " + min + " and " + max + " is: " + result.ToString());
Console.ReadLine();
}

How can i make the user to give the right value?

The problem is that the courselist[y] works only for 0 value or 1 if i add a second courselist.How i can obligate the user to give the right value?
Also if the courselist is empty , what i have to do to show the appropiate message?
public static void AddTrainer()
{
Console.WriteLine("Trainer name");
string sname = Console.ReadLine();
Trainer tr = new Trainer(Helper.trainerlist.Count() + 1, sname);
Helper.trainerlist.Add(tr);
Console.WriteLine("Give course");
int y = Convert.ToInt32(Console.ReadLine());
//y = y - 1;
Helper.courselist[y].trainerIDlist.Add(Helper.trainerlist.Count());
Helper.ShowMenu2();
}
You could ask again until the user provides the correct value
string input;
do
{
Console.WriteLine("Give course (0 or 1)");
input = Console.ReadLine();
}
while (input != "0" && input != "1");
int y = Convert.ToInt32(input);
Console.WriteLine("Give course");
int y;
while (!int.TryParse(Console.ReadLine(), out y) || y >= Helper.courselist.Count() || y < 0)
{
Console.WriteLine("Give course that already created (1,2,3,...etc)");
}
Helper.courselist[y].trainerIDlist.Add(Helper.trainerlist.Count());
This worked , but i want to give 1 for the first courselist , not 0. And what if the courselist is empty?

Using correct number in calculation c#

A user enters two prime numbers which are then multiplied together, and another calculation of (a-1) * (b-1) is completed (a and b being the prime numbers entered). a function to checks the numbers entered, if the numbers are NOT prime, the user will be asked to re-enter the numbers. However, when I test this, I've noticed that if the user inputs a number which ISN'T prime, and then re-enters a prime number, the calculations are based on the number which ISN'T prime. E.g. if the user enters 2 and 4, since 4 isn't prime they are asked to enter another number, e.g 3, the calculations will be based on the numbers 2 and 4.
How can I correct this so it takes the valid prime number and not the invalid number originally entered?
namespace example
{
class Program
{
class Co_P
{
static void coprime(ref int c, int calculation)
{
if (gcd(c, calculation) == 1)
Console.WriteLine("it's Co-Prime");
else
do
{
Console.WriteLine("it isn't Co-Prime");
Console.WriteLine("Enter a Co-Prime");
c = int.Parse(Console.ReadLine());
coprime(ref c, calculation);
} while (gcd(c, calculation) != 1);
}
static int Prime_a(int a) //check a is prime
{
if (a <= 1) return 0;
for (int i = 2; i <= a / 2; i++)
{
if (a % i == 0)
{
return 0; //not prime
}
}
return 1;
}
static void result(int a) //outputs if a is prime/or not
{
if (Prime_a(a) != 0)
{
Console.WriteLine(a + " is a prime number");
}
else do
{
Console.WriteLine(a + " isn't prime number");
Console.WriteLine();
Console.WriteLine("Please make sure you enter a prime number");
a = int.Parse(Console.ReadLine());
} while (Prime_a(a) == 0);
}
static int Prime_b(int b)
{
if (b <= 1) return 0;
for (int i = 2; i <= b / 2; i++)
{
if (b % i == 0)
{
return 0;
}
}
return 1;
}
static void resultb(int b)
{
int result = Prime_b(b);
if (Prime_b(b) != 0)
{
Console.WriteLine(b + " is a prime number");
}
else do
{
Console.WriteLine(b + " is not a prime number");
Console.WriteLine("Please make sure you enter a prime number");
b = int.Parse(Console.ReadLine());
} while (Prime_b(b) == 0);
}
static void Main(string[] args)
{
int a;
Console.WriteLine("Enter a prime number for a");
a = int.Parse(Console.ReadLine());
Console.WriteLine();
result(a);
Console.WriteLine();
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
int total = a * b;
Console.WriteLine("The total of the prime numbers is = " + total);
int calculation = (a - 1) * (b - 1); //calculation
Console.WriteLine();
Console.WriteLine("The result = " + calculation);
Console.WriteLine();
}
}
}
You should extend result and resultb function so it returns new prompted valid number
static int result(int a) {
var result = Prime_a(a);
if (result != 0)
...code...
return result
}
Also don't forget to reassign those values
...code...
a = result(a);
...code...
b = resultb(b);
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(b);
Console.WriteLine();
In line resultb(b); you are passing int to method resultb. int is a value type, or in other words, passing int to a method means passing its value to a method, where copy of that value is created. In this case a copy of b is created in method resultb. Every further change on b inside method resultb is made on copy and original stays the same.
In resultb method pass parameter by reference by adding ref keyword. Instead
static void resultb(int b)
{
// code
}
method will look like this
static void resultb(ref int b)
{
// code
}
You will call the method this way
resultb(ref b);
Here's the portion of code.
int b;
Console.WriteLine("Enter a prime number for b");
b = int.Parse(Console.ReadLine());
Console.WriteLine();
resultb(ref b);
Console.WriteLine();
Now every change on passed b inside method resultb will reflect on the original.
You should do the same for method result(int a).

How find average of numbers(by input) and also count numbers

I mean how to count and sum input numbers until receive "end".
thanks !
And also how to find out input is number or letter in c#?
class Program
{
static void Main(string[] args)
{
int n = 0;
int sum = 0;
string inp;
do
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num= Convert.ToInt16(inp);
sum = sum + num;
n++;
} while (too == "end");
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
}
}
I would suggest you use a normal while loop and also add validation to check to integer input.
For the while loop you want to loop until the input is not equal to "end":
while(inp != "end")
For the validation, you can use int.TryParse method:
int num = 0;
if (int.TryParse(inp, out num)) { }
Here is a modified example of your code:
int n = 0;
int sum = 0;
string inp = null;
while(inp != "end")
{
Console.Write("Numbers ");
inp = Console.ReadLine();
int num = 0;
if (int.TryParse(inp, out num))
{
sum = sum + num;
n++;
}
}
int average = sum / n;
Console.WriteLine(" " + average);
Console.ReadLine();
// A list to hold all of the numbers entered
List<int> numbers = new List<int>();
// Will hold the inputted string
string input;
// This needs to be outside the loop so it's written once
Console.Write("Numbers: " + Environment.NewLine);
// Keep going until we say otherwise
while (true)
{
// Get the input
input = Console.ReadLine();
// Will hold the outcome of parsing the input
int number = -1;
// Check to see if input was a valid number
bool success = int.TryParse(input, out number);
// If it was a valid number then remember it
// If ANY invalid or textual input is detected then stop
if (success)
numbers.Add(number);
else
break;
}
// Write the count and average
Console.WriteLine("Count:" + numbers.Count);
Console.WriteLine("Average:" + numbers.Average());
Console.ReadLine();
Input:
Numbers:
1
2
3
4
5
Output:
Count: 5
Average: 3
The only thing here a little different to what you specified is ANY invalid or textual entry causes it to finish, not just typing the word "end", although that obviously works too.

Categories

Resources