This question already has answers here:
Getting the input from user till valid input received
(4 answers)
How can I make a program loop back to the start if else is true? C#
(2 answers)
Closed 1 year ago.
I know how to check if user input is not valid but I don't know how to ask again.
In my code if user input is string then it says "Invalid input" and exits the console
But I want it to ask again "Please enter your first number: " until answer is number!
I tried while loop but I failed.
Can anyone show me how to do it please ?
int Summation = 0;
Console.Write("\n\t\t\tPlease enter your first number: ");
string firstNumberInput = Console.ReadLine();
if (!int.TryParse(firstNumberInput, out int FirstNumber))
{
Console.WriteLine("\n\t\t\tInvalid input!");
Console.Beep();
Environment.Exit(0);
}
Console.Write("\n\t\t\tPlase enter your second number: ");
string secondNumberInput = Console.ReadLine();
if (!int.TryParse(secondNumberInput, out int SecondNumber))
{
Console.WriteLine("\n\t\t\tInvalid input!");
Console.Beep();
Environment.Exit(0);
}
Console.Write("\n\t\t\tNow chose your operator(+, -, *, /): ");
string Operator = Console.ReadLine();
switch (Operator)
{
case "+":
Summation = FirstNumber + SecondNumber;
break;
case "-":
Summation = FirstNumber - SecondNumber;
break;
case "*":
Summation = FirstNumber * SecondNumber;
break;
case "/":
Summation = FirstNumber / SecondNumber;
break;
default:
Console.WriteLine("\n\t\t\tThe operator is not valid!");
Console.Beep();
Environment.Exit(0);
break;
}
Console.WriteLine("\n\t\t\tYour answer is {0}", Summation);
Any time you want to repeat an action, what you're talking about is a "loop". For a loop you just need a body of code to repeat and a condition on which to remain in the loop. For example, consider something like this:
// declare your variables
var firstNumber = 0;
var validInput = false;
// loop until you have valid input
while (!validInput)
{
// get the input
Console.Write("\n\t\t\tPlease enter your first number: ");
var firstNumberInput = Console.ReadLine();
// validate it
validInput = int.TryParse(firstNumberInput, out firstNumber);
// if it was invalid, notify the user
if (!validInput)
{
Console.WriteLine("\n\t\t\tInvalid input!");
Console.Beep();
}
}
This would continuously loop until the input is valid.
Related
I am a beginner in C# and I am currently writing an ATM console where customer:
1 - Check Account Balance
2 - Withdraw Money
3 - Paying In
4 - Press Q to exit
I got stuck at the second option because if the user enters a higher amount than the account balance, I would like C# to repeat the question until it gets a valid reply from the user. I used do-while loop but I still haven't managed to get it right
My code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ATM
{
internal class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Barclays, please choose one of the options",
"/n 1 - Check Account Balance",
"/n 2 - Withdraw Money" +
"/n 3 - Paying In" +
"/n 4 - Press Q to exit");
string optionChosen = Console.ReadLine();
int customerBalance = 5000;
switch (optionChosen)
{
case "1":
Console.WriteLine("Your balance is " + customerBalance);
break;
case "2":
Console.WriteLine("Please enter the amount you would like withdraw: ");
int amountEntered = Convert.ToInt32(Console.ReadLine());
if(amountEntered > customerBalance)
do
{
Console.WriteLine("Insufficent balance please enter another amount: ");
amountEntered++;
}while(amountEntered < 5);
else
{
Console.WriteLine("Your new balance is " + (customerBalance - amountEntered));
}
break;
case "3":
Console.WriteLine("Pleas enter the amount you would like to pay in: ");
int amountPaidIn = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Your new balance is " + (customerBalance + amountPaidIn));
break;
case "4":
Console.WriteLine("Thank you, have a nice day");
break;
default:
Console.WriteLine("Please enter a valid name");
break;
}
Console.ReadKey();
}
}
}
Here is one solution.
You need to loop across the whole case statement logic. I'm also not sure what use amountEntered++ is? So I have used a boolean to detect whether the amount is valid and used that as the condition in the do while loop.
case "2":
bool validAmount = true;
do
{
Console.WriteLine("Please enter the amount you would like withdraw: ");
int amountEntered = Convert.ToInt32(Console.ReadLine());
if(amountEntered > customerBalance)
{
Console.WriteLine("Insufficient balance - please enter another amount:");
validAmount = false;
}
else
{
Console.WriteLine("Your new balance is " + (customerBalance - amountEntered));
}
} while(!validAmount);
break;
I'm Working on a project for college and have sat here trying to figure out a solution to this problem for a solid 3 hours now. the problem is:
Scenario:
You want to calculate a student’s GPA (Grade Point Average) for a number of classes taken by the student during a single semester.
Inputs:
The student’s name.
Class names for the classes taken by the student.
Class letter grade for the classes taken by the student.
Class credit hours for the classes taken by the student.
Processing:
Accept and process classes until the user indicates they are finished.
Accumulate the number of credit hours taken by the student.
Calculate the total number of “points” earned by the student as:
a. For each class calculate the points by multiplying the credit hours for that class times the numeric equivalent of the letter grade. (A=4.0, B=3.0, C=2.0, D=1.0, F=0)
b. Total all points for all classes.
Calculate the GPA as the total number of “points” divided by the total credit hours.
Output:
Display a nicely worded message that includes the student’s name and the GPA (decimal point number with 2 decimal places) achieved by the student that semester.
What I currently have is:
static void Main(string[] args)
{
String StudentName;
//Error Trapping
try
{
Console.WriteLine("Welcome to The GPA Calculator");
Console.WriteLine("Hit any key to continue...");
Console.ReadKey();
Console.Write("Please enter your name: ");
StudentName = Convert.ToString(Console.ReadLine());
InputGradeInfo();
}
//Error Repsonse
catch (System.Exception e)
{
Console.WriteLine("An error has Occurred");
Console.WriteLine("The error was: {0}" , e.Message);
//Belittle the User
Console.WriteLine("Good Job, you Broke it.");
Console.ReadLine();
}
}
public static double InputGradeInfo()
{
String ClassName;
Char LetterGrade;
Double LetterGradeValue;
Double CreditHours;
Double ValueOfClass;
Console.Write("Please enter the class title: ");
ClassName = Convert.ToString(Console.ReadLine());
Console.Write("Please enter the total credits this class is worth: ");
CreditHours = Convert.ToDouble(Console.ReadLine());
Console.Write("Please enter the grade letter recived: ");
LetterGrade = Convert.ToChar(Console.ReadLine());
switch (LetterGrade)
{
case 'a': LetterGradeValue = 4;
break;
case 'A': LetterGradeValue = 4;
break;
case 'b': LetterGradeValue = 3;
break;
case 'B': LetterGradeValue = 3;
break;
case 'c': LetterGradeValue = 2;
break;
case 'C': LetterGradeValue = 2;
break;
case 'd': LetterGradeValue = 1;
break;
case 'D': LetterGradeValue = 1;
break;
case 'f': LetterGradeValue = 0;
break;
case 'F': LetterGradeValue = 0;
break;
default: LetterGradeValue = 0;
break;
}
ValueOfClass = CalculateClass(LetterGradeValue, CreditHours);
return ValueOfClass;
}
public static double CalculateClass(double LetterGrade, double CreditHours)
{
Double CreditTotal;
CreditTotal = CreditHours * LetterGrade;
return CreditTotal;
}
The Problem arises for me as to how one would loop info collection, save it to different variable every time and then breaking the loop using user input at the end. We haven't learned about arrays yet so that's off the table. After I have that looped collection down calculating the total GPA and displaying wouldn't be difficult.
Also I haven't learned about created classes yet so I can't use those either
static void Main(string[] args)
{
String StudentName;
//Error Trapping
try
{
Console.WriteLine("Welcome to The GPA Calculator");
Console.WriteLine("Hit any key to continue...");
Console.ReadKey();
Console.Write("Please enter your name: ");
StudentName = Convert.ToString(Console.ReadLine());
List<double> gradeInfoList = new List<double>();
List<double> creditList = new List<double>();
bool brakeLoop = false;
while (!brakeLoop)
{
gradeInfoList.Add(InputGradeInfo(creditList));
Console.WriteLine("Do you want to continue(y/n): ");
brakeLoop = Console.ReadLine() != "y";
}
Console.WriteLine(StudentName + " GPA is: " + gradeInfoList.Sum() / creditList.Sum());
}
//Error Repsonse
catch (System.Exception e)
{
Console.WriteLine("An error has Occurred");
Console.WriteLine("The error was: {0}", e.Message);
//Belittle the User
Console.WriteLine("Good Job, you Broke it.");
Console.ReadLine();
}
}
public static double InputGradeInfo(List<double> creditList)
{
String ClassName;
Char LetterGrade;
Double LetterGradeValue;
Double CreditHours;
Double ValueOfClass;
Console.Write("Please enter the class title: ");
ClassName = Convert.ToString(Console.ReadLine());
Console.Write("Please enter the total credits this class is worth: ");
CreditHours = Convert.ToDouble(Console.ReadLine());
creditList.Add(CreditHours);
Console.Write("Please enter the grade letter recived: ");
LetterGrade = Convert.ToChar(Console.ReadLine().ToUpper());
switch (LetterGrade)
{
case 'A': LetterGradeValue = 4;
break;
case 'B': LetterGradeValue = 3;
break;
case 'C': LetterGradeValue = 2;
break;
case 'D': LetterGradeValue = 1;
break;
case 'F': LetterGradeValue = 0;
break;
default: LetterGradeValue = 0;
break;
}
ValueOfClass = CalculateClass(LetterGradeValue, CreditHours);
return ValueOfClass;
}
public static double CalculateClass(double LetterGrade, double CreditHours)
{
Double CreditTotal;
CreditTotal = CreditHours * LetterGrade;
return CreditTotal;
}
Here you probably want this. You need one while loop to take all the classes, the loop brakes if you say that you don't want to continue or put another input. You make the gradeInfoList with gradeInfoList.Sum() function.
Also your variables should start with small letter, StudentName->studentName !
EDIT:
gpa List is collection which stores all your values which comes from InputGradeInfo().
What Sum() function is doing:
double sum = 0;
foreach(double d in gpa)
{
sum= sum + d; //(or sum+= d;)
}
In other words loop all the elements in gradeInfoList collection and make the sum of them.
About the while loop-> this loop will executes till the condition in the brackets is broken. In this case you can add many classes till you click 'y' at the end. If you click something else from 'y' you will break the loop.
I add another list creditList which you will add as parameter to the InputGradeInfo. In this list you will store every credit per class. At the end you will have gradeInfoList .Sum()/creditList.Sum() and this will give you what you want.
have a small program im playing with. need to make sure it checks if number, if not loop untill their is a number on each input and create a main method and calculator method any help?
code is here /////////////////////////////////////////////////////
int num1;
int num2;
string operand;
float answer;
string text1;
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
// if number not integer then fail ////
bool res = int.TryParse(text1, out num1);
if (!res)
{
Console.WriteLine(" FAIL");
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
}
else
{
}
//// enter operand ////
Console.Write("Please enter an operand (+, -, /, *): ");
operand = Console.ReadLine();
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
// if number not integer then fail //
bool eff = int.TryParse(text1, out num2);
if (!eff)
do
{
Console.WriteLine(" FAIL");
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
}
while (eff == true);
{
}
// converts number to integer ///
// makes operand answers from each number ////
switch (operand)
{
case "-":
answer = num1 - num2;
break;
case "+":
answer = num1 + num2;
break;
case "/":
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
default:
answer = 0;
break;
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " =
"+ answer.ToString());
Console.ReadLine();
}
}
}
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " =
" + answer.ToString());
Console.ReadLine();
If this is all you need and you are using a Console App, you can use:
int num1;
int num2;
string operand = string.Empty;
float answer;
string text1;
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
// if number not integer then fail ////
bool res = int.TryParse(text1, out num1);
while (!res)
{
Console.WriteLine(" FAIL");
////enter first number ////
Console.Write("Please enter a number: ");
text1 = Console.ReadLine();
res = int.TryParse(text1, out num1);
}
//// enter operand ////
while (operand == string.Empty || operand.Length > 1 || !(new char[] { '+', '-', '*', '/' }).Contains(char.Parse(operand)))
{
Console.Write("Please enter an operand (+, -, /, *): ");
operand = Console.ReadLine();
}
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
// if number not integer then fail //
bool eff = int.TryParse(text1, out num2);
while (!eff)
{
Console.WriteLine(" FAIL");
// enter second number //
Console.Write("Please enter the second number: ");
text1 = Console.ReadLine();
eff = int.TryParse(text1, out num2);
}
// converts number to integer ///
// makes operand answers from each number ////
switch (operand)
{
case "-":
answer = num1 - num2;
break;
case "+":
answer = num1 + num2;
break;
case "/":
if (num2 == 0)
{
Console.WriteLine("Divide By Zero Error");
return;
}
answer = num1 / num2;
break;
case "*":
answer = num1 * num2;
break;
default:
answer = 0;
break;
}
/// converts numbers to string using operand and writes final line ///
Console.WriteLine(num1.ToString() + " " + operand + " " + num2.ToString() + " = "+ answer.ToString());
Console.ReadLine();
Why do you need to create a separate method for something so simple. And I found this too simple to be asked, so just asking if this is what was required? You could have struggled a bit more and written this yourself. There is nothing trivial in this. I am just assuming that you are new to programming.
the problem appears to be with the handling of "eff" and "res". If the user keys a non integer value the first time they're asked it doesn't matter what they answer the second time as num1 and num2 aren't populated with the value. Fix that and the code appears to work.
As entering the values appears to be doing the same thing but with a slightly different prompt you should move this into a seperate function, something like this:
static int GetNumberFromUser(string order)
{
string userText = String.Empty;
int result;
Console.Write("Please enter {0} number: ", order);
userText = Console.ReadLine();
while (!int.TryParse(userText, out result))
{
Console.WriteLine("FAILED");
Console.Write("Please enter {0} number: ", order);
userText = Console.ReadLine();
}
return result;
}
You would then call it by calling
num1 = GetNumberFromUser("first");
num2 = GetNumberFromUser("second");
This function takes care of converting to a number and keeps asking until the user keys in a valid value.
The "Calculator" method would just be copied and pasting the switch you have into a seperate method:
static float Calculator(int num1, string operand, int num2)
{
switch (operand)
{
case "-":
return num1 - num2;
case "+":
return num1 + num2;
case "/":
return num1 / num2;
case "*":
return num1 * num2;
default:
return 0;
}
}
Called using
answer = Calculator(num1, operand, num2);
Whilst I'm at it, the result line is difficult to read, I'd go for something like this
Console.WriteLine("{0} {1} {2} = {3}", num1, operand, num2, answer);
I have 2 codes that I want to combine into 1 and am having a lot of trouble doing it. The code should ask for the group number then their donation amount and loop back until they press 0. Once they press 0 it should show the total for all groups. Here are the 2 different codes
code 1
using System;
public class TotalPurchase
{
public static void Main()
{
double donation;
double total = 0;
string inputString;
const double QUIT = 0;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
while(donation != QUIT)
{
total += donation;
Console.WriteLine("Enter next donation amount, or " +
QUIT + " to quit ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
}
Console.WriteLine("Your total is {0}", total.ToString("C"));
}
}
code 2
using System;
namespace donate
{
class donate
{
public static void Main()
{
begin:
string group;
int myint;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
goto begin;
default:
Console.WriteLine("Incorrect grade number.", myint);
goto begin;
}
}
}
}
So basically I want to find the total for each group using the 2nd code.
Any help would be greatly appreciated.
Don't use goto like that. Just use another while loop like you did in the first code segement.
It would be much more concise to say:
if (myInt > 3 && myInt < 7) { ... }
instead of using that switch statement.
Basically your code for summing up the donation amount does the trick, so just stick that inside a similar loop that handles what the group number is. If you do this you're going to want to use a different input to signify the end of donations vs the end of input altogether. It would be confusing if the application said "Enter 0 to quit input", followed by "Enter 0 to quit donation input".
You are very close with Code 2. If you put Code 2 inside while loop it works!
The only code I have written for you here is declared myint outside the while loop and initialised it to a non-zero value.
double total = 0;
int myint = -1;
while (myint != 0)
{
string group;
Console.WriteLine("Please enter group number (4, 5, or 6)");
Console.WriteLine("(0 to quit): ");
group = Console.ReadLine();
myint = Int32.Parse(group);
switch (myint)
{
case 0:
Console.WriteLine("Bye.");
break;
case 4:
case 5:
case 6:
double donation;
string inputString;
Console.WriteLine("Please enter the amount of the contribution: ");
inputString = Console.ReadLine();
donation = Convert.ToDouble(inputString);
total += donation;
break;
default:
Console.WriteLine("Incorrect grade number.", myint);
break;
}
}
Console.WriteLine("Your total is {0}", total.ToString("C"));
I am working on a homework assignment, beginning C#.
Have to accept input from user:
phone number with numbers or characters
then return only the numeric version of number.
My program takes input and returns value, but does not end when 10 characters have been entered.
You can enter as many characters as you want, then when enter is pressed it only displays first 10.
It also does not test the cases after each character entered. Seems to do at the end.
I would like to have each character tested after input and then once ten characters have been entered
the program display results.
I hope I am giving enough info. I am pretty stressed about this.
It is due tomorrow and I have a few other programs to do yet.
Any help would be greatly appreciated.
My code:
Console.Write("Please enter your phone number: ");
do
{
int temp = Console.Read();
input = Convert.ToChar(temp);
//int tempInput = Convert.ToString(tempInput);
switch (input)
{
case '0':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += input.ToString();
counter--;
break;
// { other cases }
default:
// if input does not match cases then loop returns to
// request new input
Display.Error(input.ToString());
Console.Write(alphaNumericPhoneNumber);
//Display.Continue();
//Console.Clear();
input = ' ';
break;
}
}
while (numericPhoneNumber.Length < 0);
return numericPhoneNumber;
}
The documentation for the Console.Read() method explains the described behavior.
The Read method blocks its return while you type input characters; it terminates when you press the Enter key. [...] Subsequent calls to the Read method retrieve your input one character at a time.
If you want to process the characters as they arrive, you may use the KeyAvailableand ReadKey methods as demonstrated in the documentation. The example is available in 5 .NET languages, including C#.
Basically you need to use Console.ReadKey() instead of Console.Read() as the latter expects a \n from an ENTER press to return and the former returns immediately when key is pressed.
class Program
{
static void Main(string[] args)
{
ReadPhone();
Console.ReadLine();
}
private static void ReadPhone()
{
var numericPhoneNumber = string.Empty;
Console.Write("Please enter your phone number: ");
do
{
var keyInfo= Console.ReadKey();
if (char.IsDigit(keyInfo.KeyChar))
{
numericPhoneNumber += keyInfo.KeyChar;
}
else
{
Console.WriteLine();
Console.WriteLine("Please enter numeric numbers only");
}
}
while (numericPhoneNumber.Length <= 10);
Console.WriteLine("Phone Number: {0}", numericPhoneNumber);
}
}
static void Main(string[] args)
{
int i=0;
string str=String.Empty;
Char c;
Console.WriteLine("Enter number:");
while (i < 10)
{
if (char.IsDigit(c = Console.ReadKey().KeyChar))
{
str += c;
i++;
}
}
Console.WriteLine("str: "+str);
}
Thanks to everyone for your help.
I ended up using the readkey to evaluate each character and assign its respective numerical value as per the telephone keypad.
I don't think that I was very clear about it in my original post... little stressed about it at the time... spent to long on this question.
The replies to this post showed some pretty clean code. I hope to get to that level soon.
I will show what I ended up doing, just incase someone in interested.
Thanks again for your help.
class Request
{
public static void GetPhoneNumber(out string UserInput, out string ConvertedString)
{
// create instance of ConsoleKeyInfo
ConsoleKeyInfo cki = new ConsoleKeyInfo();
string alphaNumericPhoneNumber = " ";
string numericPhoneNumber = " ";
char input = ' ';
Console.Write("Please enter your phone number: ");
// perform a do... while loop to read 10 characters of input
do
{
cki = Console.ReadKey();
input = cki.KeyChar;
switch (char.ToUpper(input))
{
case '0':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += input.ToString();
break;
case '1':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += input.ToString();
break;
case 'A':
case 'B':
case 'C':
case '2':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "2";
break;
case 'D':
case 'E':
case 'F':
case '3':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "3";
break;
case 'G':
case 'H':
case 'I':
case '4':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "4";
break;
case 'J':
case 'K':
case 'L':
case '5':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "5";
break;
case 'M':
case 'N':
case 'O':
case '6':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "6";
break;
case 'P':
case 'Q':
case 'R':
case 'S':
case '7':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "7";
break;
case 'T':
case 'U':
case 'V':
case '8':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "8";
break;
case 'W':
case 'X':
case 'Y':
case 'Z':
case '9':
alphaNumericPhoneNumber += input.ToString();
numericPhoneNumber += "9";
break;
default:
// if input does not match cases then loop returns to
// request new input
Console.Clear();
Display.Error(input.ToString());
// display for user to continue... displays valid numbers so far
Console.Write("Continue with phone number: " + alphaNumericPhoneNumber);
input = ' '; // returns blank character and not added to strings so not counted
break;
}
}
while (numericPhoneNumber.Length < 11); // counts until string has 10 digits
UserInput = alphaNumericPhoneNumber;
ConvertedString = numericPhoneNumber;
}
}
Ok, not so sure about helping you with your homework. I used to sell my assignments to other kids when I was studying, so I guess I can't take the moral high ground here.
Here's a solution, but make sure you do some googling and understand how it works.
// Initialise the result to nothing.
string result = string.Empty;
do
{
// Prompt for input.
Console.WriteLine("Please enter your 10-digit phone number: ");
// Read the response.
string input = Console.ReadLine();
// Replace any characters that are not numbers with the empty string (remove them).
result = System.Text.RegularExpressions.Regex.Replace(input, "[^0-9]", string.Empty);
}
while (result.Length != 10);
// Do something with the result.
Console.WriteLine("You typed: '{0}'.", result);
If you want to read one character at a time (which sounds a bit odd to me), then you could do something like:
// Initialise the result to nothing.
string result = string.Empty;
// Prompt for input.
Console.WriteLine("Please enter your 10-digit phone number: ");
do
{
string input = Console.ReadKey().KeyChar.ToString();
// Replace any characters that are not numbers with the empty string (remove them).
result += Regex.Replace(input, "[^0-9]", string.Empty);
}
while (result.Length != 10);
// Do something with the result.
Console.WriteLine("You typed: '{0}'.", result);