How to validate user input to only allow numbers - c#

I have a method here that allows the user to enter any number except for 999. But I don't know how to create a validation when user enters a negative number or letter.
static int EnterScores(double[] scores, int maxScores)
{
double userInput;
int count = 0;
while (count < maxScores)
{
Console.Write("Enter a score(or 999 to quit): ");
userInput = double.Parse(Console.ReadLine());
if (userInput == 999 || userInput < 0)
break;
scores[count++] = userInput;
}
return count;
}

You can use double.TryParse. If it can convert string to float - it will be true
...
var str = Console.ReadLine();
if (double.TryParse(str, out userInput)){
if (userInput == 999 || userInput < 0)
break;
scores[count++] = userInput;
}
...

If user inputs a letter or something that can't be converted to double your this piece of code double.TryParse will throw an exception and program will fail.
So you should use try-catch block here:
try
{
userInput = double.Parse(Console.ReadLine());
if (userInput == 999)
{
break;
}
else if (userInput < 0)
{
Console.WriteLine("Invalid input");
}
else
{
scores[count++] = userInput;
}
}
catch(Exception e) // will take care of letters
{
Console.WriteLine("You enter an Invalid input !"):
}

Separate the tests for userInput == 999 and userInput < 0, like this:
...
if (userInput == 999)
{
break;
}
else if (userInput < 0)
{
Console.WriteLine("Invalid input");
}
else
{
scores[count++] = userInput;
}
...

Related

While loop doesnt function when calculatin all positive numbers c#

I am making a while loop. The purpose of the loop is to take all the positive numbers and calculating the average. It works most of the time but not always. Can someone help? here is the code:
double count = 0;
int sum = 0;
int input = -1;
while (input != 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
if (input < 0)
{
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
}
}
if (input == 0)
{
Console.Write($"Average of all positive numbers is: { (sum += input) / count:0.00} ");
}
The second if is redundant it should work just like this
while (input != 0) {
Console.Write("Enter a number: ");
input = int.Parse(Console.ReadLine());
if (input > 0)
{
sum += input;
count++;
}
}
Your problem was when you enter a negative number it gives you the option to enter another, but then you enter a new iteration of the while loop and it asks you to enter another number. Removing the second if should fix your problem. Hope i helped :)
This code does not throw exceptions when non numeric data is entered
int count = 0;
long sum = 0;
int input;
Console.Write("Enter a number: ");
while (int.TryParse(Console.ReadLine(), out input))
{
Console.Write("Enter a number: ");
if (input > 0)
{
sum += input;
count++;
}
}
Console.Write($"Average of all positive numbers is: {sum} / {Math.Max(count,1.0)} = {Math.Round( sum / Math.Max(count,1.0), 2)}.");

How to stop a while loop? C#

I am very new to C# and while loops. Does anyone know how to stop it? It keeps printing the first if-statement. Here is the code:
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = 0;
input = int.Parse(Console.ReadLine());
while (input != 0)
{
Console.WriteLine("Enter a number: ");
if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
if (input > 0 && input % NoLeapYear != 0)
{
Console.WriteLine($"{input} is not a leap year.");
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
if (input == 0)
{
Console.WriteLine("End of program");
}
}
You have to read the input inside the while loop:
const int Year = 400;
const int LeapYear = 4;
const int NoLeapYear = 100;
int input = -1; // initialize to something different than zero, to enter the while loop (or use do while loop instead of while loop)
while (input != 0)
{
Console.WriteLine("Enter a number: ");
input = int.Parse(Console.ReadLine()); // you were missing this line
if (input > 0 && input % LeapYear == 0 || input % Year == 0)
{
Console.WriteLine($"{input} is a leap year.");
}
if (input > 0 && input % NoLeapYear != 0)
{
Console.WriteLine($"{input} is not a leap year.");
}
if (input < 0)
{
Console.WriteLine("Year must be positive!");
}
if (input == 0)
{
Console.WriteLine("End of program");
}
}
Consider using a do while loop in this case.
If you are using loop just and break to true statement It will breaks it
while (input != 0) {
conditions;
break; // Breaks the loop
}
Use the break; keyword to stop any loop in C# not just C# in many languages also break is used to stop loops
Or,
Satisfy the condition to opposite of what you have it will break/stop the loop
use break (https://www.w3schools.com/cs/cs_break.php)
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
if (i == 4)
{
break;
}
}

Console.ReadLine() not exiting Program in c#

I have an assignment where I have to create code to display factors and whether a number is a perfect and/or prime number. I think I have all the code right to run my program, but when I get to the last line (Console.ReadLine()) I expect to hit enter and then exit the program. Currently, when I hit enter, the program displays whether it is a prime number and/or perfect number over and over again (each time you hit enter). So basically, it executes everything after the while loop over and over again.
Keep in mind, I'm very new to C#, so some of my syntax and readability may be weird. I am only interested in answers that will help me solve the ReadLine issue. My instructors will help me with making my code more readable and organized.
Thanks for your advice! Here is my code. I commented where the ReadLine isn't closing the program:
using System;
namespace Factorizer.UI
{
class Program
{
static void Main(string[] args)
{
string input;
int num, i, x = 0, sum = 0;
while (true)
{
Console.Write("Enter a number: ");
input = Console.ReadLine();
if (int.TryParse(input, out num))
{
Console.Write("\nThe factors are: ");
for (i = 1; i <= num; i++)
{
if (num % i == 0)
{
Console.Write("{0} ", i);
}
}
break;
}
else
{
Console.WriteLine("\nThat was not a valid number!\n");
}
}
for (i = 1; i < num; i++)
{
if (num % i == 0)
{
sum = sum + i;
}
if (sum == num)
{
Console.Write("\n\n{0} is a perfect number.\n", num);
}
else
{
Console.Write("\n\n{0} is not a perfect number.\n", num);
}
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
x++;
break;
}
}
if (x == 0 && num != 1)
{
Console.Write("\n{0} is a prime number.", num);
}
else
{
Console.Write("\n{0} is not a prime number.", num);
}
Console.ReadLine(); //this isn't closing the program!
}
}
}
}
Console.ReadLine() is inside the for loop. Move it down after the next bracket.
Just put Console.ReadLine(); after the for, it's inside the for block that's why it keeps printing and remove the for that you have after the while block, like this:
string input;
int num, i, x = 0, sum = 0;
while (true)
{
Console.Write("Enter a number: ");
input = Console.ReadLine();
if (int.TryParse(input, out num))
{
Console.Write("\nThe factors are: ");
for (i = 1; i <= num; i++)
{
if (num % i == 0)
{
Console.Write("{0} ", i);
}
}
break;
}
else
{
Console.WriteLine("\nThat was not a valid number!\n");
}
}
/*for (i = 1; i < num; i++)
{*/
if (num % i == 0)
{
sum = sum + i;
}
if (sum == num)
{
Console.Write("\n\n{0} is a perfect number.\n", num);
}
else
{
Console.Write("\n\n{0} is not a perfect number.\n", num);
}
for (i = 2; i <= num / 2; i++)
{
if (num % i == 0)
{
x++;
break;
}
}
if (x == 0 && num != 1)
{
Console.Write("\n{0} is a prime number.", num);
}
else
{
Console.Write("\n{0} is not a prime number.", num);
}
Console.ReadLine(); //this isn't closing the program!
//}

c# console add or subtract calculator

I am a c# beginner so I have a problem in my c# console calculator here is the code
Console.WriteLine("If you want to add click 1 , subtract click 2");
int userchoice = int.Parse(Console.ReadLine());
if (userchoice == 1)
{
Console.WriteLine("Enter a number");
int firstinput = int.Parse(Console.ReadLine());
Console.WriteLine("Enter another number");
int secondinput = int.Parse(Console.ReadLine());
Console.WriteLine("Click =");
string choice = Console.ReadLine();
if (choice == "=")
{
Console.WriteLine(firstinput + secondinput);
}
else if (userchoice == 2)
{
Console.WriteLine("Enter a number");
int firstinput1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter another number");
int secondinput1 = int.Parse(Console.ReadLine());
Console.WriteLine("Click =");
string choice2 = Console.ReadLine();
if (choice2 == "=")
{
Console.WriteLine(firstinput1 - secondinput1);
}
The problem is if I entered 1 it will make the addition operation but if I entered 2 it won't do anything why although I am writing its code as what is right answer.
you have mixed the else statements. Right now your else if (userchoice == 2) matches statement if (choice == "="). Try:
if (userchoice == 1)
{
Console.WriteLine("Enter a number");
int firstinput = int.Parse(Console.ReadLine());
Console.WriteLine("Enter another number");
int secondinput = int.Parse(Console.ReadLine());
Console.WriteLine("Click =");
string choice = Console.ReadLine();
if (choice == "=")
{
Console.WriteLine(firstinput + secondinput);
}
}
else if (userchoice == 2)
{
Console.WriteLine("Enter a number");
int firstinput1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter another number");
int secondinput1 = int.Parse(Console.ReadLine());
Console.WriteLine("Click =");
string choice2 = Console.ReadLine();
if (choice2 == "=")
{
Console.WriteLine(firstinput1 - secondinput1);
}
}
else
{
Console.WriteLine("Wrong Selection, either select 1 or 2");
}
#FatmaHamdy , You missed the } before the else part
Console.WriteLine("If you want to add click 1 , subtract click 2");
int userchoice = int.Parse(Console.ReadLine());
if (userchoice == 1)
{
Console.WriteLine("Enter a number");
int firstinput = int.Parse(Console.ReadLine());
Console.WriteLine("Enter another number");
int secondinput = int.Parse(Console.ReadLine());
Console.WriteLine("Click =");
string choice = Console.ReadLine();
if (choice == "=")
{
Console.WriteLine(firstinput + secondinput);
}
}
else if (userchoice == 2)
{
Console.WriteLine("Enter a number");
int firstinput1 = int.Parse(Console.ReadLine());
Console.WriteLine("Enter another number");
int secondinput1 = int.Parse(Console.ReadLine());
Console.WriteLine("Click =");
string choice2 = Console.ReadLine();
if (choice2 == "=")
{
Console.WriteLine(firstinput1 - secondinput1);
}
}

Not using a duplicate number when using a decrement

I am trying to write a program using a loop with a decrement and not to be able to use the same number twice. If using the same number, I would want a "invalid number" displayed. It is a number system set up to read numbers between 10 and 100. If it goes over 100, "invalid number" is displayed. This is what I have so far:
string userNumber;
int userNumberInt;
int previousNumber = 0;
for (int counter = 0; counter <= 10; counter++)
{
Console.WriteLine("Enter your number");
userNumber = Console.ReadLine();
userNumberInt = Convert.ToInt32(userNumber);
if ((userNumberInt <= 100) && (userNumberInt >= 10))
{
Console.WriteLine("Your number is " + userNumber);
previousNumber = userNumberInt;
}
else if
(previousNumber == userNumberInt)
{
Console.WriteLine("Number is invalid.");
}
// number is invalid
else
// number is valid
{
Console.WriteLine("Invalid number.");
counter--;
}
}
Console.ReadLine(); // for last enter key
}
}
}
With your use of previous, the same numbers could be entered. For example, the first number entered could be 12, so 12 becomes previousNumber. Then when you enter 12 again you'll display "invalid number" which is good, but you enter 13, then 13 becomes the previousNumber and now you can enter 12 again. So what you should do is store all of your valid numbers in a list and check if your userInput is in the list so that you're not using duplicate numbers.
public static void Main(string[] args)
{
List<int> validInputs = new List<int>();
for (int counter = 0; counter <= 10; counter++)
{
Console.Write("Enter a number: ");
string stringInput = Console.ReadLine();
int numberInput;
if (int.TryParse(stringInput, out numberInput))
{
if ((10 <= numberInput && numberInput <= 100) &&
validInputs.Contains(numberInput) == false)
{
Console.WriteLine("Number is valid");
validInputs.Add(numberInput);
}
else
{
// This is not a valid number cause it's not in the range or it's a duplicate
Console.WriteLine("Invalid number");
counter--;
}
}
else
{
// This is not a valid number
Console.WriteLine("Invalid number");
counter--;
}
}
}

Categories