My program has to add the previous number entered to the next one. This is what I have so far, and I got stuck. It adds up the number that I have entered, but I don't understand how I have to validate one number from previous.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
inputInt += inputInt;
Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);
} while (inputInt != QUIT);
}
Since there may be an indefinite number of entries, I don't know how to properly use an array.
If you are trying to find sum of numbers take another variable.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0,tempint=0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out tempint);
if (inputBool == true)
{
inputInt += tempint;
}
Console.WriteLine("Sum of the past three numbers is: {0}", inputInt);
} while (tempint!= QUIT);
}
If you want the simplest solution, you can just keep track of the past 3 numbers and sum them up when you print
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int i1 = 0;
int i2 = 0;
int i3 = 0;
int inputInt = 0;
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
{
i3 = i2;
i2 = i1;
i1 = inputInt;
}
Console.WriteLine("Sum of the past three numbers is: {0}", i1+i2+i3);
} while (inputInt != QUIT);
}
This answer uses LINQ and Queues to do what you want.
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
int inputInt = 0;
Queue myQ = new Queue();
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
{
if (myQ.Count() == 3)
{
myQ.Dequeue();
myQ.Enqueue(inputInt);
}
else
{
myQ.Enqueue(inputInt);
}
}
if (myQ.Count() == 3)
{
Console.WriteLine("Sum of the past three numbers is: {0}", myQ.Sum());
}
} while (inputInt != QUIT);
}
Use a list to store all of the numbers as they come in. Then at the end count how many items are in the list, and Sum() the entire list
static void Main(string[] args)
{
const int QUIT = -1;
string inputStr;
List<int> allNumbers = new List<int>();
do
{
Console.Write("Type a number (type -1 to quit): ");
inputStr = Console.ReadLine();
bool inputBool = int.TryParse(inputStr, out inputInt);
if (inputBool == true)
allNumbers.Add(inputInt); // Add a new element to the list
Console.WriteLine("Sum of the past " + allNumbers.Count + " numbers is: {0}", allNumbers.Sum());
} while (inputInt != QUIT);
}
you need to create a local variable to hold the output from int.TryParse. Also you do not need a do while loop, you can exit immediately when the input is -1. With these changes, keeping up with the last 3 numbers becomes much easier:
static void Main(string[] args)
{
const int QUIT = -1;
int[] last3 = new int[3];
// infinite loop, exit is done when input is -1
for(;;) {
Console.Write("Type a number (type -1 to quit): ");
var input = Console.ReadLine();
int tmp; // holds the int value of the input
if (int.TryParse(input, out tmp))
{
if (tmp == QUIT)
break; // input is -1
// input was an int, so lets move the last two towards
// the front of the array, last3[0] contained the oldest value
// which is gone now
last3[0] = last3[1];
last3[1] = last3[2];
// now overwrite the last item in the array with the newest value
last3[2] = tmp;
}
// add up the values, note if input was not a valid int, this will sum
// the last 3 valid values because the above if statement will only execute
// and change the values in the array if the user input was a number
var sum = last3[0] + last3[1] + last3[2];
Console.WriteLine("Sum of the past three numbers is: {0}", sum);
}
}
Related
The goal of the code is to take a string of numbers separated by hyphens and check if they are consecutive.
I have tried using string.spit, iterating over the array and checking if the number +1 is equal to the next value. But I've run into an issue of the index I'm working on exceeding the bounds of the array.
Here is the current build.
public static void Consecutive()
{
Console.Write("enter multiple numbers separated by hyphens: ");
var userinput = Console.ReadLine();
var nums = userinput.Split();
int index = 0;
bool isConsecutive = false;
foreach(var number in nums)
{
if(Convert.ToInt32(nums[index + 1]) == Convert.ToInt32(nums[index] + 1))
{
isConsecutive = true;
}
else
{
isConsecutive = false;
}
if(index == nums.Length)
{
break;
}
}
Console.WriteLine(isConsecutive);
}
You want to split by hyphens, but you split by white-spaces. You also don't use the number loop variable of the foreach. For what you are doing a for-loop is much more appropriate anyway:
public static void Consecutive()
{
Console.WriteLine("enter multiple numbers separated by hyphens: ");
string userinput = Console.ReadLine();
string[] nums = userinput.Split('-');
// always validate input
while (!nums.All(n => n.All(char.IsDigit)))
{
Console.WriteLine("All numbers must be valid integers");
userinput = Console.ReadLine();
nums = userinput.Split('-');
}
bool isConsecutive = true;
for(int i = 1; i < nums.Length; i++)
{
int thisInt = int.Parse(nums[i]);
int prevInt = int.Parse(nums[i - 1]);
if(thisInt != prevInt + 1)
{
isConsecutive = false;
break;
}
}
Console.WriteLine(isConsecutive);
}
This is because when the foreach loop iterates over the last element there is no element with index + 1 and your check if(index == nums.Length) does not work.
Explanation:
nums.Length = last index + 1.
For an array with 5 elements, the length = 5 and the last index = 4.
Because of that your if condition is never true.
Solution:
Change the condition from if(index == nums.Length) to if(index == nums.Length - 1)
Here's a different approach, generating the expected sequence and seeing if that matches the cleansed input:
var delimiter = ",";
Console.Write("Enter multiple integers separated by '" + delimiter + "': ");
var userinput = Console.ReadLine(); ;
bool isConsecutive = false;
try
{
var strNums = userinput.Split(delimiter.ToCharArray());
var nums = Array.ConvertAll(strNums, x => int.Parse(x));
var consecutive = Enumerable.Range(nums[0], nums.Length);
var strCleansed = String.Join(delimiter, nums);
var strGenerated = String.Join(delimiter, consecutive);
isConsecutive = (strCleansed == strGenerated);
Console.WriteLine(" cleansed = " + strCleansed);
Console.WriteLine(" generated = " + strGenerated);
}
catch (Exception)
{
Console.WriteLine("Invalid Integer in Input");
}
Console.WriteLine("isConsecutive = " + isConsecutive);
Console.ReadKey();
Sample runs:
Enter multiple integers separated by ',': -3, -0000002, -1, 0, 1, 02, 3
cleansed = -3,-2,-1,0,1,2,3
generated = -3,-2,-1,0,1,2,3
isConsecutive = True
Enter multiple integers separated by ',': 1,2,3,5
cleansed = 1,2,3,5
generated = 1,2,3,4
isConsecutive = False
Enter multiple integers separated by ',': 1,fish,2,fish,red fish,blue fish
Invalid Integer in Input
isConsecutive = False
I'm having trouble with looping my program so that it breaks out of the loop if user enters "quit" or "exit".
When I type any string, my program crashes as it tries to parse the string input to an int. Any advice?
namespace DiceRolling
{
/* We’re going to write a program that makes life easier for the player of a game like this. Start the
program off by asking the player to type in a number of dice to roll.Create a new Random
object and roll that number of dice.Add the total up and print the result to the user. (You should
only need one Random object for this.) For bonus points, put the whole program in a loop and allow them to keep typing in numbers
until they type “quit” or “exit”. */
class DiceRolling
{
static void RollDice(int numTries)
{
Random random = new Random();
//Console.Write("Please enter the number of dice you want to roll: ");
//int numTries = Convert.ToInt32(Console.ReadLine());
int sum = 0;
int dieRoll;
for (int i = 1; i <= numTries; i++)
{
dieRoll = random.Next(6) + 1;
Console.WriteLine(dieRoll);
sum += dieRoll;
}
Console.WriteLine("The sum of your rolls equals: " + sum);
}
static void Main(string[] args)
{
while (true)
{
Console.Write("Please enter the number of dice you want to roll: ");
string input = Console.ReadLine();
int numTries = Convert.ToInt32(input);
//bool isValid = int.TryParse(input, out numTries);
RollDice(numTries);
Console.ReadKey();
if (input == "quit" || input == "exit")
break;
}
}
}
}
Tigrams is pretty close, this is slightly better
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
while (input != "quit" && input != "exit")
{
int numTries = 0;
if (int.tryParse(input, out numTries)
{
RollDice(numTries);
}
Console.Write("Please enter the number of dices you want to roll: ");
input = Console.ReadLine();
}
tried to make it as similar as possible to what you have
while (true)
{
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
int numTries;
if (int.TryParse(input, out numTries))
{
RollDice(numTries);
}
else if(input == "quit" || input == "exit")
{
break;
}
}
while (true)
{
Console.Write("Please enter the number of dices you want to roll: ");
string input = Console.ReadLine();
if (input == "quit" || input == "exit") //check it immediately here
break;
int numTries = 0;
if(!int.TryParse(input, out numTries)) //handle not valid number
{
Console.WriteLine("Not a valid number");
continue;
}
RollDice(numTries);
Console.ReadKey();
}
Try int numTries =int.Parse(input != null ? input: "0");
I wrote this little program that catches five integer numbers that are entered consecutively at the console.
This works as expected - except for one thing:
I did not find a way to accept 0 as one of the numbers being entered.
Of course, a solution with another collection type is easy.
But the challenge here is to do it with an array of five integers.
I tried to set a boolean flag "zeroEntered", tried with a counter, tried to count j backwwards. It all does not work.
Perhaps this is not possible? Would somebody know for sure?
Here is the code:
class Program
{
static void Main(string[] args)
{
#region Catch5IntegerInArrayOfInt[5]
// I try to catch five integers in an array of int[5]
// This works as expected except I cannot catch 0 as one of the numbers
// Cannot wrap my head around this one it seems
// because all ints are initialized with 0
Console.WriteLine("Please enter five unique numbers consecutively.");
int[] fiveNumbers = new int[5]; // do it using an array just the same (as collections were not part of the lectures so far)
for (int i = 0; i < fiveNumbers.Length; i++)
{
Console.WriteLine("Please enter your {0} number:", (Countables)i);
CatchUsersNumbers(fiveNumbers, i);
}
DisplayResult(fiveNumbers);
Console.WriteLine("\n");
}
#endregion
#region HelperMethods
private static bool CheckWhetherInteger(string userInput)
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
return result;
}
private static bool CheckUniqueness(int[] fiveNumbers, int userInput)
{
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (userInput == 0)
{
for (int j = i ; j <fiveNumbers.Length; j--)
{
if (j == 0)
break;
if (fiveNumbers[j] == 0)
{
return false;
}
}
}
else if (fiveNumbers[i] == userInput)
{
return false;
}
}
return true;
}
private static void CatchUsersNumbers(int[] fiveNumbers, int i)
{
while (true)
{
userInput = Console.ReadLine().Trim();
if (CheckWhetherInteger(userInput) && CheckUniqueness(fiveNumbers, myInteger))
{
fiveNumbers[i] = myInteger;
break;
}
else
Console.Clear();
Console.WriteLine("You did not enter a unique integer number, try again...");
}
}
private static void DisplayResult(int[] fiveNumbers)
{
Console.Clear();
Array.Sort(fiveNumbers);
Console.WriteLine("These are the five interger numbers you entered \nand that were stored in the array:\n");
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (i != fiveNumbers.Length - 1)
Console.Write(fiveNumbers[i] + ", ");
else
Console.Write(fiveNumbers[i]);
}
}
#endregion
#region Class Variables
private static int myInteger = 0;
private static string userInput;
private enum Countables
{
first = 0,
second,
third,
fourth,
fifth
}
#endregion
}
Thank you.
It is possible, but your array of 5 ints will be initialized to 5 zeroes, so when scanning for uniqueness, your check fails, especially because of this piece of code:
if (fiveNumbers[j] == 0)
{
return false;
}
So instead of looping through the entire array, you should keep a counter to keep track of how many items you already have in your array. Then, when performing the check, only check upto that index, and don't include the other items in the check, because they contain 0, but you should treat them as uninitialized.
You could also solve this using other data types. For instance, you could create an array of nullable integers, so you can actually check whether an item already got a value. Or (maybe the best solution) you could use a List instead of array.
Your Only error here is that int.TryParse() takes 0 as invalid you could make another if statement to handle the exception but this looks less clean
private static bool CheckWhetherInteger(string userInput)
{
if (userInput == "0")
{
myInteger = 0;
return true
}
else
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
}
return result;
}
I just post the solution - using nullable integers - as suggested by Golez Trol. Here it is, should somebody be interested:
class Program
{
static void Main(string[] args)
{
#region Catch5IntegerInArrayOfInt[5]
// The solution to catching five integers in an array of int[5]
// is to use nullable integers.
// Keeping a counter when entering an integer to the array does not appeal to me.
// With normal integers I cannot catch 0 as one of the numbers
// because all ints are initialized with 0
Console.WriteLine("Please enter five unique numbers consecutively.");
var fiveNumbers = new int?[5]; // do it using an array just the same (as collections were not part of the lectures so far)
for (int i = 0; i < fiveNumbers.Length; i++)
{
Console.WriteLine("Please enter your {0} number:", (Countables)i);
CatchUsersNumbers(fiveNumbers, i);
}
DisplayResult(fiveNumbers);
Console.WriteLine("\n");
}
#endregion
#region HelperMethods
private static void CatchUsersNumbers(int?[] fiveNumbers, int i)
{
while (true)
{
userInput = Console.ReadLine().Trim();
if (CheckWhetherInteger(userInput) && CheckUniqueness(fiveNumbers, myInteger))
{
fiveNumbers[i] = myInteger;
break;
}
else
{
Console.Clear();
Console.WriteLine("You did not enter a unique integer number, try again...");
}
}
}
private static bool CheckWhetherInteger(string userInput)
{
bool result = Int32.TryParse(userInput, out myInteger);
if (result == false)
{
Console.Clear();
Console.WriteLine("You did not enter an integer.");
}
return result;
}
private static bool CheckUniqueness(int?[] fiveNumbers, int userInput)
{
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (fiveNumbers[i] == userInput)
{
return false;
}
}
return true;
}
private static void DisplayResult(int?[] fiveNumbers)
{
Console.Clear();
Array.Sort(fiveNumbers);
Console.WriteLine("These are the five interger numbers you entered \nand that were stored in the array:\n");
for (int i = 0; i < fiveNumbers.Length; i++)
{
if (i != fiveNumbers.Length - 1)
Console.Write(fiveNumbers[i] + ", ");
else
Console.Write(fiveNumbers[i]);
}
}
#endregion
#region Class Variables
private static int myInteger = 0;
private static string userInput;
private enum Countables
{
first = 0,
second,
third,
fourth,
fifth
}
#endregion
}
Thank you for your hints - I was truly stuck.
I would like my program to fill an array with user input, but with an numeric input (then program will make specific calculations with that numbers, but it's not important for now).
If no input is done, program should stop reading numbers and print it. I have a couple of errors, especially in case of parsing, because I have tried a couple of solutions, and I have no idea in which part of code and maybe what way, numbers in an array should be parsed to avoid receiving an "cannot implicitly convert type string to int" or "cannot implicitly convert type int[] to int".
This how my code looks like:
public static void Main (string[] args)
{
int[] userInput = new int[100];
int xuserInput = int.Parse (userInput);
for (int i = 0; i<userInput.Length; i++)
{
userInput[i] = Console.ReadLine ();
if (userInput == "")
break;
}
Console.WriteLine (userInput);
}
you should take the input to a string and try to parse it to integer:
public static void Main(string[] args)
{
int[] userInput = new int[100];
int counter = 0;
for (counter = 0; counter < userInput.Length; counter++)
{
string input = Console.ReadLine();
if (input == "")
break;
else
int.TryParse(input, out userInput[counter]);
}
for (int i = 0; i < counter; i++)
{
Console.WriteLine(userInput[i]);
}
Console.ReadLine();
}
try parse will not throw exception like parse will.
if you decide to use parse, catch exceptions
Try this:
int[] userInputs = new int[100];
int parsedInput;
int inputs = 0;
bool stop = false;
while (inputs < 100 && !stop)
{
string userInput = Console.ReadLine();
if (userInput == "")
{
stop = true;
}
else if (Int32.TryParse(userInput, out parsedInput))
{
userInputs[i] = parsedInput;
inputs++;
}
else
{
Console.WriteLine("Please enter a number only!");
}
}
for each (int number in userInputs)
{
Console.WrietLine(number.ToString());
}
This code does a few things.
First, a while loop is used to ensure the user inputs 100 numbers or doesn't enter any data.
Next, it gets the input from the user. If it's an empty input, it sets the stop flag to true, which will exit the loop.
If the input wasn't empty, it uses TryParse to determine if the input is a number. If it is, it returns true and the converted input is added to the array and the counter incremented.
If the parse fails, the user is prompted to enter a number.
Once the array is filled, it loops through the array and prints out each input.
The problem is that you are parsing userInput which is an array with int.Parse instead of parsing the input you got by Console.ReadLine()
int xuserInput = int.Parse (userInput); // Remove this statement.
For parsing user input you need to parse like this
string input = Console.ReadLine ();
if (input == "")
break;
else
int.TryParse(input, out userInput[i]);
try this.
public static void Main (string[] args)
{
int[] userInput = new int[100];
int xuserInput = int.Parse (userInput);
for (int i = 0; i<userInput.Length; i++)
{
int temp = int.Parse(Console.ReadLine());
userInput[i] = temp;
if (userInput == "")
break;
}
Console.WriteLine (userInput);
}
You just might want to use this
static void Main(string[] args)
{
int[] userInput = new int[100];
string recievedInput = "";
for (int i = 0; i<userInput.Length; i++)
{
recievedInput = Console.ReadLine();
int.TryParse(recievedInput, out userInput[i]);
if (recievedInput == "")
break;
}
Console.WriteLine (userInput); //this will only print the type name of Userinput not all element
}
The following program reads numbers from user.
If user enters an invalid number, then it reports with the message: Not a valid number.
If user enters nothing, then the program prints all the numbers entered by the user.
class Program
{
static void Main(string[] args)
{
int[] userInput = new int[10];
for(int count = 0; count <= 9; count++)
{
int number;
string input = Console.ReadLine();
bool result = Int32.TryParse(input, out number);
if (result)
{
userInput[count] = number;
}
else if (!result)
{
if (input != string.Empty)
Console.WriteLine("Not a valid number.");
else if (input.Equals(string.Empty))
{
foreach (var item in userInput)
{
Console.WriteLine(item.ToString());
}
Console.WriteLine("Press any key to continue...");
Console.ReadKey(true);
return;
}
}
}
}
}
Please let me know, if this is okay to you.
The program I've written is set to only accept positive integers as input. If the user inputs a letter instead, then it crashes. Negative integers don't cause any problems, though it's not 'valid' in regards to how my program functions.
What I want to do is:
Prevent the program from crashing from invalid input.
Display an error message if the input is invalid
Have the program continue where it left off, without affecting the rest of the program.
Also, a part of my program involves division. Is there a way to prevent the user from entering all zeros?
This is in C#
My code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue;
do
{
Console.WriteLine("Enter Striking Level: ");
string striking = Console.ReadLine();
Console.WriteLine("Enter Grappling Level: ");
string grappling = Console.ReadLine();
Console.WriteLine("Enter Submission Level: ");
string submission = Console.ReadLine();
Console.WriteLine("Enter Durability Level: ");
string durability = Console.ReadLine();
Console.WriteLine("Enter Technical Level: ");
string technical = Console.ReadLine();
Console.WriteLine("Enter Speed Level: ");
string speed = Console.ReadLine();
Console.WriteLine("Enter Hardcore Level: ");
string hardcore = Console.ReadLine();
Console.WriteLine("Enter Charisma Level: ");
string charisma = Console.ReadLine();
int gra = Convert.ToInt32(grappling);
int str = Convert.ToInt32(striking);
int dur = Convert.ToInt32(durability);
int spd = Convert.ToInt32(speed);
int tec = Convert.ToInt32(technical);
int hdc = Convert.ToInt32(hardcore);
int cha = Convert.ToInt32(charisma);
int sub = Convert.ToInt32(submission);
int total = str + gra + sub + dur + tec + spd + cha + hdc;
int overall = total / 8 + 8;
Console.WriteLine("The Overall is " + overall);
Console.WriteLine("Do you wish to continue? y/n? ");
if (Console.ReadLine() == "y")
{
shouldContinue = true;
}
else break;
} while (shouldContinue == true);
}
}
}
int value = 0;
if (!int.TryParse(input, out value))
{
MessageBox.Show("Oops");
} else {
// use the value in the variable "value".
}
static void Main(string[] args)
{
bool validInput = false;
string inputString;
UInt32 validPositiveInteger = 0;
while (!validInput)
{
Console.WriteLine("Please enter a positive 32 bit integer:");
inputString = Console.ReadLine();
if (!UInt32.TryParse(inputString, out validPositiveInteger))
{
Console.WriteLine("Input was not a positive integer.");
}
else if (validPositiveInteger.Equals(0))
{
Console.WriteLine("You cannot enter zero.");
}
else
{
validInput = true;
//Or you could just break
//break;
}
}
Console.WriteLine(String.Format("Positive integer = {0}", validPositiveInteger));
}
Here you go:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace OverallCalculator
{
class Program
{
static void Main(string[] args)
{
bool shouldContinue = true;
while (shouldContinue)
{
int strikingLevel = GetValue("Enter Striking Level: ");
int grapplingLevel = GetValue("Enter Grappling Level: ");
int submissionLevel = GetValue("Enter Submission Level: ");
int durabilityLevel = GetValue("Enter Durability Level: ");
int technicalLevel = GetValue("Enter Technical Level: ");
int speedLevel = GetValue("Enter Speed Level: ");
int hardcoreLevel = GetValue("Enter Hardcore Level: ");
int charismaLevel = GetValue("Enter Charisma Level: ");
int total = strikingLevel + grapplingLevel + durabilityLevel + submissionLevel +
technicalLevel + speedLevel + charismaLevel + hardcoreLevel;
int overall = total / 8 + 8;
Console.WriteLine("\nThe Overall is {0}.", overall);
while (true)
{
Console.WriteLine("Do you wish to continue? y/n? ");
string response = Console.ReadLine();
if (response.Equals("y", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("yes", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = true;
break;
}
else if (response.Equals("n", StringComparison.CurrentCultureIgnoreCase) ||
response.Equals("no", StringComparison.CurrentCultureIgnoreCase))
{
shouldContinue = false;
break;
}
}
}
}
private static int GetValue(string prompt)
{
while (true)
{
Console.WriteLine(prompt);
string input = Console.ReadLine();
int value;
if (int.TryParse(input, out value))
{
if (value <= 0)
Console.WriteLine("Please enter a positive number.");
else
return value;
}
else
{
Console.WriteLine("Please enter a number.");
}
}
}
}
}
Yes... before you do anything calculations, you need to validate the data you are going to use. If any data is incorrect, then you display a messagebox detailing the errors and return focus to the form so the user can fix the errors. Repeat as necessary.
I wrote this one many moons ago when I first learned C#. It is a conversion from a VB function that I got back in VB5 days. The major benefit of the function is that there is no error - an input will just not allow any characters outside of the predefined list.
/***********************************************************************
* bool ValiText(char inChar,
* string valid,
* bool editable,
* bool casesensitive
* Description: Validate Input Characters As They Are Input
* Notes: For each control whose input you wish to validate, just put
* e.Handled = ValiText(e.KeyChar, "0123456789/-" [,true][,true])
* In The KeyPress Event
***********************************************************************/
public bool ValiText(char inChar, string valid, bool editable, bool casesensitive)
{
string inVal = inChar.ToString();
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
/// Case InSensitive - Make Them Both The Same Case
if (!casesensitive)
{
tst = tst.ToLower();
inVal = inVal.ToLower();
}
return tst.IndexOf(inVal,0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid, bool editable)
{
string tst = valid;
/// Editable - Add The Backspace Key
if (editable) tst += ((char)8).ToString();
return tst.IndexOf(inChar.ToString(),0,tst.Length) < 0;
}
public bool ValiText(char inChar, string valid)
{
return valid.IndexOf(inChar.ToString(),0,valid.Length) < 0;
}
Note That This Will Not Work On A Web APP.