C# input has to be 5 digits - c#

I have a question that asks the user to enter a student number, how can I make it so it will only accept a 5 digit number. The input is being added to an object like
console.writeline("Enter the student number: ");
then
studentObject.StudentNumber = int.Parse(Console.Readline());
I've tried using
if (Console.ReadLine().Length != 5)
{
//Do this
}
else
{
//Do this
}
But it won't work, the .Length says can't convert type int to bool. I'm stuck, any help please?

You can use regular expressions:
String input;
do {
Console.WriteLine("Please enter student number:");
input = Console.ReadLine();
}
while (!Regex.IsMatch(input, #"^\d{5}$")); // <- five digits expected
// input contains 5 digit string
int number = int.Parse(number);
P.S. In case that the input should be "five digit number, not starting with zero" the regular expression has to be changed to something like that:
while (!Regex.IsMatch("12345", #"^[1-9]\d{4}$")); // five digits, not zero-starting

Probably not the answer to your question, however one thing I noticed:
if you are using Console.Readline() in your if-statement and then want to store it in the studentObject you will need to store it in a variable first. Calling Console.Readline(); again to store it in the studentObject will cause another input to be expected, which nullifies your attempt to validate the input.
Something like this:
static void Main(string[] args)
{
Console.WriteLine("Please enter student number:");
//get the user input
var number = Console.ReadLine();
if (number.Length != 5)
{
Console.WriteLine("Invalid format.");
}
else
{
Console.WriteLine("Yay it works");
}
Console.ReadLine();
}

var input = Console.ReadLine();
int i;
if (input.Length > 0 && input.Length < 6 && Int32.TryParse(input, out i))
// i has 5 digit;
else
// i has zero

char[] cc = Console.Read().ToString().ToCharArray();
if (char.IsDigit(cc[0])&&
char.IsDigit(cc[1])&&
char.IsDigit(cc[2])&&
char.IsDigit(cc[3])&&
char.IsDigit(cc[4]))
{
//Life's GOOD!
}else { //bad input}
Note: I'm self-taught & don't have much knowledge. Correct me if wrong.

Related

How do I make the program request user input after inputting invalid data in C#?

I am not sure how to tackle this problem. I tried putting the do while loop in the method GetUserInput and then putting the for loop in the do while loop. It doesn't reset the question it just takes the number and adds it the numbers before it. Its a supposed to be a calculator program.
//This propgram will be used to make a calculator for the class project.
//The numbers are stored as floats as well as the result. Then displayed on console.
//V1 adds a do-while loop that repeats as long as the user wants.
//V2 adds a if and else logic for when the user input a character other than a number the program will close.
//V3 added a for-loop to increase the amount of numbers that can be considered in the calculation. It makes an array
//V4 added methods to get user input and sum the numbers
class MainClass
{
public static void Main(string[] args)
{
Console.WriteLine("Hello Ulises Sanchez");
//Define 3 floating point numbers to capture the 2 inputs and the result
//floats are used to capture a broader range of numbers
float[] userInput = new float[10];
//stores the number of inputs the user requests
int numberOfUserInputs;
//define strings to store data read and also user prompts
string inputString;
string doMorefunctions = "Add More Numbers Together - y = yes - anything else for no";
//variable to test the condition to continue with calculations
bool moreActions;
do
{
Console.Clear();
numberOfUserInputs = GetuserInput(userInput);
//adds the numbers together
Summation(userInput, numberOfUserInputs);
//reset moreAction
moreActions = false;
Console.WriteLine(doMorefunctions);
inputString = Console.ReadLine();
if (inputString == "y" || inputString == "Y")
moreActions = true;
} while (moreActions);
}
//Gets the number of user inputs and stores each in the userInput array
static int GetuserInput(float[] inputArray)
{
int numberOfInputs;
string userInputPrompt = "How many numbers do you want to enter?";
//string continueMessage = "Hit any key to continue";
string errorMessage = "Invalid Input";
string inputString;
bool TryAgain;
Array.Clear(inputArray, 0, 10);
//Gets number of inputs from user
Console.Write(userInputPrompt);
inputString = Console.ReadLine();
numberOfInputs = int.Parse(inputString);
//Get inputs
for (int i = 0; i < numberOfInputs; i++)
{
Console.Write("Enter variable number {0}: ", i + 1);
inputString = Console.ReadLine();
if (Single.TryParse(inputString, out float result))
{
//if input is valid convert to float
inputArray[i] = float.Parse(inputString);
}
else
{
TryAgain = false;
Console.WriteLine(errorMessage);
inputString = Console.ReadLine();
if (inputString == "y" || inputString == "Y") TryAgain = true;
//if input is not valid input exit program
//Console.WriteLine(continueMessage);
//Console.ReadLine();
//System.Environment.Exit(1);
}
}
return numberOfInputs;
}
//takes the user input and performs a summation calculation
static void Summation(float[] inputArray, int numberOfInputs)
{
float summationResult = 0.0f;
for (int i = 0; i < numberOfInputs; i++)
{
summationResult += inputArray[i];
}
//display result to the screen
Console.WriteLine("Summation = {0}", summationResult);
}
}
We have this concept of "don't repeat yourself" (DRY) so we look for ways to make code that repeats itself not do so. Every one of your methods repeats the print/ReadLine process for asking a question
Let's have a method that asks the user for a string:
public string Ask(string q){
Console.WriteLine(q);
return Console.ReadLine();
}
Now we can say:
string name = Ask("what is your name? ");
Suppose blank input is invalid, let's use a loop to repeat the question:
public string Ask(string q){
string a = "";
while(string.IsNullOrEmpty(a)){
Console.WriteLine(q);
a = Console.ReadLine();
}
return a;
}
If the user gives no answer, they are stuck in the loop and the question is repeated until they give a valid answer
Now let's reuse this to ask for an int:
public int AskInt(string q){
return int.Parse(Ask(q));
}
Here we reuse Ask within AskInt so we don't do the print/read thing again and we leverage the "cannot renter blank" validation we already write
This however explodes if the user enters non ints
So let's use int.TryParse and keep looping while they enter garbage that doesn't parse;
public int AskInt(string q){
bool success = false;
into a=0;
while(!success){
success = int.TryParse(Ask(q), out a);
}
return a;
}
The user can only get to the last line if they enter an int
If you also want to add range validation, for example, you can put an int min, int max into your method parameters and inside the loop do success = success && a <= && a >= min
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);
The idea is to write one method that does one thing really well I.e. "ask the user for a string" and then reuse that when we write the next method that does one thing well, so we end up with two methods that do two things well. Giving the methods a sensible name allows us to package up that bit of logic they do into a few words and make out code read like a book. It doesn't need as many comments then
//ask the user what their next guess is
int guess = AskInt("enter a number between 1 and 10: ", 1, 10);
This comment isn't needed; we can easily deduce the same just by reading the code.

How to prevent input of null enter in C# [duplicate]

This question already has answers here:
check for valid number input - console application
(5 answers)
Allow To Only Input A Number - C#
(1 answer)
Closed 2 years ago.
I have just started a table programme. I am just a trainee learning C# from internet, so I am not so good in this.
I just wanted the programme to run according to the user. I want that if the user hits enter simply, the programme should not crash. That is I just wanted to know how to prevent null enter. This is the code is used:
The "______" which used if for writing a line
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace tables
{
class Program
{
static void Main(string[] args)
{
goto found;
found:
Console.WriteLine("");
string textToEnter = "MULTIPLATION TABLES";
Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (textToEnter.Length / 2)) + "}", textToEnter));
Console.WriteLine("");
Console.WriteLine("________________________________________________________________________________");
Console.WriteLine("");
int num, j, i;
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32( Console.ReadLine());
while (num == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number of which table u need ? :- ");
num = Convert.ToInt32(Console.ReadLine());
}
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
while (j == 0)
{
Console.WriteLine("please enter a valid input");
Console.Write("enter the number till which the table need to be ? :- ");
j = Convert.ToInt32(Console.ReadLine());
}
i = Convert.ToInt32(j);
for (j=1; ; j++)
{
if (j > i)
{
break;
}
Console.WriteLine(num + " * " + j + " = " + num * j);
}
string str;
Console.Write("do you want to continue? (y/n) :- " );
str= Console.ReadLine();
foreach (char ch in str)
{
if (ch == 'y')
{
goto found;
}
else if (ch=='n' )
{
Console.WriteLine("");
Console.WriteLine("THANK YOU FOR USING MY PRODUCT");
}
else
{
Console.WriteLine("please enter a valid input");
}
}
Console.ReadKey();
}
}
}
As suggested in the comments, I'd use int.TryParse(), but inside a do...while() loop. Use a separate flag (boolean) to track whether the user should keep trying again:
bool invalid;
int num, j, i;
do
{
invalid = true;
Console.Write("enter the number of which table u need ? :- ");
String response = Console.ReadLine();
if (int.TryParse(response, out num))
{
invalid = false;
}
else
{
Console.WriteLine("Invalid input. Please try again.");
}
} while (invalid);
// ...repeat the above do...while() block for "j" and "i"...
When you're accepting user input, it's important to perform validation on it. You can't assume that the user will always enter correctly formatted data that your program will be able to work with. As you discovered, a user who hits enter will give you an empty string (""), which can't be parsed to anything.
C# has several ways of attempting parsing. The first, which you're using, is Convert.ToInt32(), which throws an exception if the input it receives is not, in fact, a number. You have to catch the exception with a try/catch block, like so:
try
{
num = Convert.ToInt32(Console.ReadLine());
}
catch(FormatException ex)
{
Console.WriteLine("You didn't enter a proper number!");
}
However, in general, exceptions should be, well, exceptional. They should only be relied upon when rare failures occur, because unwinding the call stack can be expensive.
I would argue that C# has a better method for you to use in this instance: Int32.TryParse()
You can see the documentation here.
TryParse takes two parameters, the thing you're trying to parse (convert), and then a number to store the value in. It returns true or false, indicating if it succeeded or failed in converting the number.
You might use it like this:
var success = Int32.TryParse(Console.ReadLine(), num);
if (success)
{
// do something with 'num' -- it has a valid value now.
}
else
{
// Warn the user, perhaps prompt them to try again
Console.WriteLine("That wasn't a valid number!");
}
You can use a methode to get a safe int value:
private static int ReadIntValue(string psMessage)
{
int lnInt;
string lsValue = string.Empty;
do
{
Console.Write(psMessage);
lsValue = Console.ReadLine();
} while (!int.TryParse(lsValue, out lnInt));
return lnInt;
}
And then use this:
num = ReadIntValue("enter the number of which table u need ? :- ");

Number guessing game using TryParse

I´m having problems with getting my code to work while using TryParse to catch if the user where to input a string instead of a int. If I use it as it looks now I only get the base value of 0 if something other than an int is input. I want it to show an error message to the user.
Have tried messing around with a number of different ways of using TryParse but none of them has really been helpfull.
static void Main(string[] args)
{
Random r = new Random();
int speltal = r.Next(1,21);
bool play = false;
int myNum;
while (!play)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
Int32.TryParse(Console.ReadLine(), out myNum);
if (myNum < guessNum)
{
Console.WriteLine("\tThe number you have guessed is to low");
Console.ReadLine();
}
if (myNum > guessNum)
{
Console.WriteLine("\tThe number you have guessed is to high");
Console.ReadLine();
}
if (myNum == guessNum)
{
Console.WriteLine("\tCongratulations you guessed the right number!");
Console.ReadLine();
}
I want it show an error message to the user if they put in anything other than a int. It also have to include TryParse according to my teatcher
You're not capturing the bool output of TryParse so you have no idea if a non-numeric value was entered. Try something like this:
bool isValid;
do
{
Console.Write("\n\tGuess a number between 1 and 20: ");
isValid = Int32.TryParse(Console.ReadLine(), out myNum);
if(!isValid)
{
Console.WriteLine("\n\tInvalid input detected. Please try again.");
}
} while(!isValid)
The TryParse method can only put integers in the passed variable (as it is of type int), so if the value passed to it can't be parsed into an integer, the default value of int (0) will be assigned to the variable.
The way TryParse tell you if it successfully parsed the number or not, is by returning a boolean indicator.
You can try this:
while (true)
{
bool valid = int.TryParse(Console.ReadLine(), out myNum);
if(valid)
break;
Console.WriteLine("Input invalid. Please try again");
}
TryParse returns a Boolean which indicates if the input string was successfully parsed or not. Both of the answers above are correct on how to handle a invalid input but, here is a cleaner version which will also uphold the rule, between 1 and 20:
while (true)
{
Console.Write("\n\tGuess a number between 1 and 20: ");
//Checks to see if the input was successfully parsed to a integer also, performs a Trim on the input as to remove any accidental white spaces that a user might have typed in, e.g. "1000 "
if (int.TryParse(Console.ReadLine().Trim(), out myNum))
{
//Checks to see if the parsed number is in the specified range
if ((myNum > 0) && (myNum < 21))
{
break;
}
Console.WriteLine("\tThe input number was out of the specified range.");
}
else
{
Console.WriteLine("\tFailed to parse the input text.");
}
//Optional, makes the thread sleep so the user has the time to read the error message.
Thread.Sleep(1500);
//Optional, clears the console as to not create duplicates of the error message and the value of Console.Write
Console.Clear();
}
// Continue here, if (myNum < guessNum) . . .
You should use the bool returned by TryParse. Something that looks like this:
Updated answer:
static void Main(string[] args)
{
Random random = new Random();
int guessNum = random.Next(1, 21);
while(true)
{
Console.WriteLine("Guess the number between 1 and 21.");
if (Int32.TryParse(Console.ReadLine(), out int input))
{
if (input == guessNum)
{
Console.WriteLine($"You guessed it right. The number is {input}");
if(ShouldContinue())
{
guessNum = random.Next();
continue;
}
else
{
break;
}
}
if (input < guessNum)
Console.WriteLine("The number you guessed is smaller.");
else
Console.WriteLine("The number you guessed is bigger");
}
else
{
Console.WriteLine("Please enter a number between 1 and 21 as your guess");
}
}
}
static bool ShouldContinue()
{
while (true)
{
Console.WriteLine($"Do you want to continue playing? (y/n)");
string continueInput = Console.ReadLine().Trim().ToLower();
if (continueInput == "y")
return true;
else if (continueInput == "n")
return false;
else
Console.WriteLine("Invalid input!. Please choose 'y' or 'n'.");
}
}
Old answer:
while (true)
{
if (Int32.TryParse(inputInt, out int myNum))
{
// your logic goes here, too low/high or correct answer.
}
}

While loop of a string containing at least six words in C#

I am attempting to code a while loop validation to validate the user's response whenever they entered a sentence with the following criteria:
The string is null or empty
Sentence must be at least six words.
I was able to able to get the the null or empty condition to work as expected, but the "must be at least six words" isn't working as intended at the moment. Whenever I type a sentence with less than six words it accepts it fine. However, If i input a sentence with six words or more it prompts the established error message when it shouldn't.
while (String.IsNullOrEmpty(sentence) || sentence.Length != 6)
{
if (String.IsNullOrEmpty(sentence))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter your desired sentence again: ");
sentence = ReadLine();
}
else
{
Console.WriteLine("\r\nThe sentece entered isn't valid. Must have a least six words!");
Console.WriteLine("Enter a sentence with a least 6 words: ");
sentence = ReadLine();
}
}
What exactly am I doing wrong?
string sentence = Console.ReadLine();
while (true)
{
if (String.IsNullOrEmpty(sentence))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter your desired sentence again: ");
}
else if (sentence.Split(' ').Length < 6)
{
Console.WriteLine("\r\nThe sentece entered isn't valid. Must have a least six words!");
Console.WriteLine("Enter a sentence with a least 6 words: ");
}
else break;
sentence = Console.ReadLine();
}
Change while (String.IsNullOrEmpty(sentence) || sentence.Length != 6) to
while (String.IsNullOrEmpty(sentence) || sentence.Split(' ').Length < 6)
sentence.Length returns the number of characters in the string. You must split the sentence into words.
string[] words = sentence.Split();
splits at white-space characters.
Therefore, you can write your loop as
while (String.IsNullOrEmpty(sentence) || sentence.Split().Length < 6)
{
...
}
Here Length is the length of string-array resulting from the split.
Note that in case the sentence is null, the short-circuit evaluation of Boolean expressions of C# will not execute the sub-expression following the ||. Therefore you will not get a null-reference-exception.
Firstly You can change you while condition like bellow...
it will give you a sentence that length less then six
while (sentence.Length < 6)
When you want to get a word that will be six word in length then try bellow condition...
sentence.Split(' ').Length >= 6
// At first try to change while condition like bellow ....then try bellow code..
public static void Main(string[] args)
{
int count = 0;
inputSteream:
Console.WriteLine("Enter your sentence: ");
string sentence = Console.ReadLine();
while (!String.IsNullOrEmpty(sentence) && sentence.Length >= 6)
{
foreach (var item in sentence.Split(' '))
{
if (item.Length >= 6)
{
Console.WriteLine("The sentece is {0}", item);
count++;
break;
}
}
break;
}
if (count == 0)
{
goto inputSteream;
}
Console.ReadKey();
}
Try like below sample code
string sentence=Console.ReadLine();
if (String.IsNullOrEmpty(sentence))
{
Console.WriteLine("Please, do not leave the sentence field empty!");
Console.WriteLine("Enter your desired sentence again: ");
sentence = Console.ReadLine();
}
else if(sentence.Length!=6)
{
Console.WriteLine("\r\nThe sentece entered isn't valid. Must have a least six words!");
Console.WriteLine("Enter a sentence with a least 6 words: ");
sentence = Console.ReadLine();
}
else
{
Console.WriteLine("Your entered string length is'{0}' and word is{1}", sentence.Length,sentence);
}

system.formatexception in while(true) loop

The subject is a little problem:
Write a program and continuously ask the user to enter a number or "ok" to exit. Calculate the sum of all the previously entered numbers and display it on the console.
Here is my code:
var sum = 0;
while (true)
{
Console.WriteLine("Enter a number or ok to exit:");
if (Console.ReadLine() == "ok") break;
sum += Convert.ToInt32(Console.ReadLine());
Console.WriteLine(sum);
}
When I tap ok, it terminate.
When I tap number and enter, it shows system.formatexception:The input string is not in the correct format.
I know one of the solution is
var sum = 0;
while (true)
{
Console.Write("Enter a number (or 'ok' to exit): ");
var input = Console.ReadLine();
if (input.ToLower() == "ok")
break;
sum += Convert.ToInt32(input);
}
Console.WriteLine("Sum of all numbers is: " + sum);
Maybe My code looks a little weired, But Why is my code wrong?
Reason is input will be "ok". Can not convert that into an integer.
first you have to store the first input value into other variable.
then convert that string into integer and get summation.
var sum = 0;
while (true)
{
Console.Write("Enter a number (or 'ok' to exit): ");
var input = Console.ReadLine();
int newVariable = 0;
if (input.ToLower() != "ok")
{
newVariable = Convert.ToInt32(input);
}
input = Console.ReadLine();
if (input.ToLower() == "ok"){
break;
sum += newVariable;
}
}
Console.WriteLine("Sum of all numbers is: " + sum);
If there any problem here please let me know.
Try this:
var sum = 0;
while (true)
{
Console.WriteLine("Enter a number or ok to exit:");
String ans = Console.ReadLine();
if (ans == "ok" || ans.ToLower() == "ok") break;
sum += Convert.ToInt32(ans);
Console.WriteLine(sum);
}
Here I've just store input entered by user in one variable and use that variable in further process.
In your first code you have take input two times, first one is in IF condition and second in parsing, that may cause the problem.
The correct way to do this is to use int.TryParse for your conversion from a string to a number. TryParse attempts to convert the string to a number, but if it cannot do so (for example, the string contains more than just numeric digits) it will fail gracefully instead of causing an exception. The other answers so far will all cause an unhandled FormatException if something non-numeric is entered other than "ok". By using int.TryParse you can handle the case where it's a valid number, as well as the case where it is invalid, and then alert the user. Here's an example within the context of your code:
// I prefer using concrete types for numbers like this, so if anyone else
// reads it they know the exact type and numeric limits of that type.
int sum = 0;
int enteredNumber = 0;
while (true)
{
Console.Write("Enter a number (or 'ok' to exit): ");
var consoleInput = Console.ReadLine();
if (consoleInput.ToLower() == "ok")
break;
if(int.TryParse(consoleInput, out enteredNumber))
{
sum += enteredNumber;
}
else
{
Console.WriteLine("You entered '" + consoleInput + "', which is not a number.");
}
}
Console.WriteLine("Sum of all numbers is: " + sum.ToString());
This is better because you know you have no control over the user's input other than to validate it yourself, and so it's better to speculatively convert the number and be alerted to success or failure without triggering an exception. Wrapping everything with a try/catch block is not a proper solution.
Your first code example, as rightly pointed out in the comments, reads a line, tests it for 'ok', then throws it away, reads another line, and uses that to add to the sum, which is not what you wanted.
After some quick research, I would say the most concise way to handle this in C# is probably something like your second code example. In F# I was able to come up with the following examples (one is a loop, the other uses sequences, i.e. IEnumerable<_>s) but I found no concise way to get the same with C# and LINQ…
let inputLoop () =
let rec aux sum =
match stdin.ReadLine () with
| "ok" -> sum
| s -> aux (sum + int s)
stdout.WriteLine (aux 0 |> string)
let inputSeq () =
fun _ -> stdin.ReadLine ()
|> Seq.initInfinite
|> Seq.takeWhile (fun s -> s <> "ok")
|> Seq.sumBy int
|> string
|> stdout.WriteLine
Try it :)
var sum = 0;
while (true)
{
Console.Write("Enter a number: or ok to exit : ");
String input = Console.ReadLine();
if (input == "ok" || input.ToLower() == "ok") break;
if(string.IsNullOrWhiteSpace(input))
continue;
sum += Convert.ToInt32(input);
}
Console.WriteLine("Total Result: " + sum);
Write a program and continuously ask the user to enter a number or "ok" to exit. Calculate the sum of all the previously entered numbers and display it on the console. Happy Coding
var sum = 0;
while (true)
{
Console.Write("Write number or write \"ok\" for exit: ");
var input = Console.ReadLine();
if (input.ToLower() != "ok")
{
sum += Convert.ToInt32(input);
continue;
}
break;
}
Console.WriteLine("All sum: " + sum + ".");
This is one way to do it. I'm just learning to do this!
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Enter number to know the sum or press ok to exit and display the sum");
int sum = 0;
while (true) // to run the program continously asking user input
{
Console.WriteLine("Enter Number: ");
var input = Console.ReadLine(); // takes user input
if (input.ToLower() == "ok") // compares user input to string ok
break; //if user input is ok, breaks the loop and sum is displayed
var inputInInt = Convert.ToInt32(input); // if user input is int, continues to convert it to integer
sum += inputInInt; // user input in interger is added to sum
}
Console.WriteLine("The sum of entered numbers is: " + sum);
Console.ReadLine();
}
}

Categories

Resources