Hey guys looking for a simple validation code for my C# Console Program
Currently have:
public Class1()
{
Console.WriteLine("Enter a, b, c or d:");
string input = Console.ReadLine();
while ((input != "a") && "b" && "c" && "d"))
{
if (input == "a" && "b" && "c" && "d")
{
Console.WriteLine("Success");
}
if (input != "a" && "b" && "c" && "d")
{
Console.WriteLine("Try again");
Console.WriteLine("Enter a, b, c or d:");
string input = Console.ReadLine();
}
}
}
Any help is appreciated! Cheers.
This is a nonsense :
while ((input != "a") && "b" && "c" && "d"))
It can be written that way :
while (aCondition && anotherCondition && yetAnotherCondition && theLastCondition))
(input != "a") is a condition, there's no problem with that, but "b" isn't a condition, it will be considered as true since it's not false or null. I think you would have write : while ((input != "a") && (input != "b") && (input != "c") && (input != "d")))
The same way that condition if (input == "a" && "b" && "c" && "d") should have be written if (input == "a" && input == "b" && input == "c" && input == "d") will provide an algo issue. input can't be at the same time equal to "a", equal to "b", equal to "c" and equal to "d".
Plus, your code won't compile since it's in a class without being wrapped into a method.
Did you read the errors message when trying to run it?
I think the simplest approach would be to create an array of chars that are allowed and validate the input against that:
char[] allowedChars = new char[] { 'a', 'b'};
while(true){
char inputChar = 'z';
if (allowedChars.Length > 1)
{
Console.WriteLine(string.Format("Enter {0} or {1}:", string.Join(", ", allowedChars.Take(allowedChars.Length - 1)), allowedChars[allowedChars.Length - 1]));
}
else
{
Console.WriteLine(string.Format("Enter {0}", allowedChars[0]));
}
var result = char.TryParse(Console.ReadLine(), out inputChar);
if (result && allowedChars.Contains(inputChar))
{
break;
}
Console.WriteLine("Try again");
}
Console.WriteLine("Success");
Console.ReadLine();
When it's a success it'll automatically break out from the while loop and print the Success message.
Firstly, your code cannot just be in a class. It needs to be in a function. Generally you'll see that looking like this
Console.WriteLine("Enter a, b, c or d:");
while ((input != "a") &&(input != "b") && (input != "c") &&(input != "d"))
{
Console.WriteLine("Try again");
string input = Console.ReadLine();
}
Console.WriteLine("Success!");
There is a lot of mistakes in your code, look at mine and try to understand it. It's pretty easy.
Console.WriteLine("Enter a, b, c or d:\r\n");
string input = Console.ReadLine();
while (input != "")
{
if (input == "a" || input == "b" || input == "c" || input == "d")
{
Console.WriteLine("Success\r\n");
}
else
{
Console.WriteLine("Fail\r\n");
}
Console.WriteLine("Enter a, b, c or d:");
input = Console.ReadLine();
}
public Class1()
{
private static List<string> allowedChars= new List<string>(){
"a","b","c","d"
};
public void Verify()
{
Console.WriteLine("Enter a, b, c or d:");
string input = Console.ReadLine();
while (!allowedChars.Contains(input))
{
Console.WriteLine("Try again");
Console.WriteLine("Enter a, b, c or d:");
input = Console.ReadLine();
}
}
}
Why do you use a while loop? It seems quite unneccessary. I do not understand your code as to what the right answer would be, but a simple switch statement should serve your purpose better
Console.WriteLine("Enter a, b, c or d:");
string input = Console.ReadLine();
switch (input)
{
case "a": Console.WriteLine("Success");
break;
case "b":
Console.WriteLine("Try again");
break;
case "c":
Console.WriteLine("Try again");
break;
case "d":
Console.WriteLine("Try again");
break;
default: Console.WriteLine("Enter a, b, c or d:");
break;
}
Console.ReadLine();
I suggest the following code:
// char: we actually input a single character, not string
char input = '\0'; // initialize to make compiler happy
// keep on asking until success
while (true) {
Console.WriteLine("Enter a, b, c or d:");
// ReadKey: We want a single character, not a string
input = Console.ReadKey();
// input is valid if it's in ['a'..'d'] range
if (input >= 'a' && input <= 'd') {
Console.WriteLine("Success");
break;
}
Console.WriteLine("Try again");
}
Edit: in generalized case (see Adriani6's comment below) the code be a little bit more complex. I guess the underlying problem being a kind of questionary, like
Compute 2 x 2 = ?
a. 3
b. 4
c. 5
d. 0
Enter a, b, c or d:
that's why I expect the valid input should ever be in some range ('a'..'d' in the example above) which I preserved.
char from = 'a';
char upto = 'd';
// char: we actually input a single character, not string
char input = '\0'; // initialize to make compiler happy
// Building a title is, probably, the only complex thing (Linq)
string title =
$"Enter {string.Join(", ", Enumerable.Range(from, upto - from).Select(c => (char) c))} or {upto}:";
// keep on asking until success
while (true) {
Console.WriteLine(title);
// ReadKey: We want a single character, not a string
input = Console.ReadKey();
// Uncomment if we want a quit without choice, say, on Escape
//if (input == 27) { // or (input == 'q') if we want to quit on q
// input = '\0';
//
// break;
//}
// input is valid if it's in [from..upto] range
if (input >= from && input <= upto) {
Console.WriteLine("Success");
break;
}
Console.WriteLine("Try again");
}
For starters, I would break out the validation code input into a separate method as you're potentially going to have to call it multiple times if the input validation fails. The same applies for retrieving the input.
As for the validation itself, a simple check that the input string matches "a" OR "b" OR "c" OR "d" will work. You can set up the method to return the boolean value that the expression evaluates to, as below.
Finally, it's just a case of calling ValidateInput until it returns true using a While loop and negating the returned value using the logical negation operator !. Negating the returned value effectively reverses the result of the ValidateInput method. In English this would read as While ValidateInput is NOT True
class Program
{
static void Main(string[] args)
{
while (!ValidateInput(GetInput()))
{
Console.WriteLine("Try again");
}
Console.WriteLine("Success");
Console.Read();
}
private static string GetInput()
{
Console.WriteLine("Enter a, b, c or d:");
return Console.ReadLine();
}
private static bool ValidateInput(string input)
{
return (input == "a" || input == "b" || input == "c" || input == "d");
}
}
Related
I am looking to see if there is a better way to figure out if which of two characters appears first in a string.
my current code for this is
string UserInput = Console.Readline;
char FirstFound;
if (UserInput.IndexOf('+') > UserInput.IndexOf('-') )
{
FirstFound = '+';
}
else
{
FirstFound = '-';
}
Is there a method that allows more than 1 input so can simplify this? Or anything else to make this shorter?
You can shorten it a little bit by understanding the code effectively has the - character as the default value, because it's the result of the else block. With that in mind, we can do this to remove the else block:
string UserInput = Console.Readline();
char FirstFound = '-';
if (UserInput.IndexOf('+') > UserInput.IndexOf('-') )
{
FirstFound = '+';
}
We could also do this, which is not shorter but will perform better:
string UserInput = Console.ReadLine();
char FirstFound;
foreach(char c in UserInput)
{
if (c == '+' || c == '-')
{
FirstFound = c;
break;
}
}
Which we can shorten to use the linq FirstOrDefault() method:
string UserInput = Console.ReadLine();
char FirstFound = UserInput.FirstOrDefault(c => "-+".Contains(c));
If you want to able to expand this to allow more than two search targets, you can add the targets to the string like so, with no additional lines of code:
string UserInput = Console.ReadLine();
char FirstFound = UserInput.FirstOrDefault(c => "-+*/x÷".Contains(c));
In C#, after I write Console.WriteLine() and I'm asked to enter several values, can I get them all in one method? For example:
double a, b, c = 0;
Console.WriteLine("please enter the values of:\n a value:\n b value: \n c value:");
thanks for the help (:
There's no BCL methods for this specific functionality, but you could use a helper function to collect these without too much repetition.
static void Main(string[] args)
{
string RequestInput(string variableName)
{
Console.WriteLine($"{variableName}:");
return Console.ReadLine();
}
Console.WriteLine("please enter the values of:");
var a = double.Parse(RequestInput("a"));
var b = double.Parse(RequestInput("b"));
var c = double.Parse(RequestInput("c"));
}
You could do something like the following, which assumes that the user will enter a string in the console like "2.3 3.4 4.5". You may need to do some checking to make sure the input is correct.
double a = 0.0, b = 0.0, c = 0.0;
Console.WriteLine("please enter the values of: a b c");
string input = Console.ReadLine();
string[] inputParts = input.Split(' ');
if (inputParts.Length > 0 && inputParts[0] != null)
{
Double.TryParse(inputParts[0], out a);
}
if (inputParts.Length > 1 && inputParts[1] != null)
{
Double.TryParse(inputParts[1], out b);
}
if (inputParts.Length > 2 && inputParts[2] != null)
{
Double.TryParse(inputParts[2], out c);
}
Console.WriteLine($"a: {a.ToString()}");
Console.WriteLine($"b: {b.ToString()}");
Console.WriteLine($"c: {c.ToString()}");
So, I am attempting to make a loop where if someone enters a char it will execute. If it is wrong it will will display not an option. If I put an Else {Console.WriteLine("Not an option") at the end of the the "end" after my Array() method, it doesn't work either.
So, I am not completely sure of what I am doing. Does this even require a loop? As I would imagine it does to work? Any suggestions would be wonderful.
class Program
{
static void Main(string[] args)
{
string _a = "";
constructor dick = new constructor();
Console.WriteLine("Enter C for constructor, M for method, A for an array...");
Console.WriteLine("Please reference source code to have full details and understanding...");
while (_a.ToUpper() == "C" || "M" || "A")
{
_a = Console.ReadLine();
if (_a.ToUpper() == "C")
{
Console.WriteLine(dick.a);
}
if (_a.ToUpper() == "M")
{
Shit();
}
if (_a.ToUpper() == "A")
{
Array();
}
}
}
public class constructor
{
public string a = "This is a constructor!";
}
static public void Shit()
{
string b = "This is a method!";
Console.WriteLine(b);
}
static public void Array()
{
Console.WriteLine("\nHow large of an array?\n");
string sSize = Console.ReadLine();
int arraySize = Convert.ToInt32(sSize);
int[] size = new int[arraySize];
Random rd = new Random();
Console.WriteLine();
for (int i = 0; i < arraySize; i++)
{
size[i] = rd.Next(arraySize);
Console.WriteLine(size[i].ToString());
}
}
}
}
instead of this:
while (_a.ToUpper() == "C" || "M" || "A")
Define a bool variable and:
bool control = true;
while (control)
{
_a = Console.ReadKey();
var character = _a.KeyChar.ToString().ToUpper();
switch (character)
{
case "C":
Console.WriteLine(dick.a);
control = false;
break;
case "M":
control = false;
Shit();
break;
case "A":
control = false;
Array();
break;
default:
Console.WriteLine("You entered wrong character");
break;
}
}
If you want to force user to enter a correct character, yes you need a loop.And use Console.ReadKey instead of Console.ReadLine if the input is just one character
I need to press t two times in order to get any output; otherwise the program goes directly into the else condition or gives an exception handler error. What am I doing wrong here?
As you guys can see there are two classes one twotable and other program which contains the main method. I am trying to get the output using the invoke method of twotable class.
namespace ConsoleApplication6
{
class twotable
{
public static void two()
{
int i;
int j;
for (i = 1; i <= 10;i++)
{
for (j = 2; j <= 2;j++ )
{
Console.WriteLine(i * j);
}
}
}
}
class Program
{
static void Main()
{
Console.WriteLine("Press t for two table");
char c = Convert.ToChar(Console.ReadLine());
{
char t = Convert.ToChar(Console.ReadLine());
if (c == t)
{
twotable.two();
}
else
{
Console.WriteLine("i hate u");
}
}
}
}
}
You are reading from the console twice.
Instead of
char t = Convert.ToChar(Console.ReadLine());
if (c == t)
You need
if (c == 't')
Do you want the user to enter in the character 't' twice on separate ReadLine()s in order to show the output? If so:
static void Main()
{
Console.WriteLine("Press t for two table");
char c1 = Convert.ToChar(Console.ReadLine());
char c2 = Convert.ToChar(Console.ReadLine());
if (c1 == 't' && c2 == 't')
{
twotable.two();
}
else
{
Console.WriteLine("i hate u");
}
}
Or do you want to read in 'tt' in one ReadLine()?
static void Main()
{
Console.WriteLine("Press t for two table");
string input = Console.ReadLine();
if (input.Equals("tt"))
{
twotable.two();
}
else
{
Console.WriteLine("i hate u");
}
}
Code is little bit messy, but loking even on this code
char c = Convert.ToChar(Console.ReadLine());
...
{
char t = Convert.ToChar(Console.ReadLine());
.....
}
you call Console.ReadLine(...) 2 times, so you need to press t 2 times.
It's hard to say, but probabbly you want to do something like:
char t = 't';
...
{
char consoleChar = Convert.ToChar(Console.ReadLine());
if(consoleChar == t) // or simple if(consoleChar == 't')
{
//do something here, we get a t symbol from console
}
.....
}
My be need to use Console.ReadKey instead, and test c == 't':
Obtains the next character or function key pressed by the user.
and your code like this:
var cki = Console.ReadKey();
if (cki.KeyChar == 't')
{
...
}
I think your problem is here - char c. You're comparing char c with char t
Both lines ask for user input.
char c = Convert.ToChar(Console.ReadLine());
I have written my codes and i want to validate it in such a way thet it will only allow intergers to be inputed and not alphabets. Here is the code, please I will love you to help me. Thanks.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace minimum
{
class Program
{
static void Main(string[] args)
{
int a = Convert.ToInt32(Console.ReadLine());
int b = Convert.ToInt32(Console.ReadLine());
int c = Convert.ToInt32(Console.ReadLine());
if (a < b)
{
if (a < c)
{
Console.WriteLine(a + "is the minimum number");
}
}
if (b < a)
{
if (b < c)
{
Console.WriteLine(b + "is the minimum number");
}
}
if (c < a)
{
if (c < b)
{
Console.WriteLine(c + "is the minimum number");
}
}
Console.ReadLine();
}
}
}
You should test if it's an int instead of converting in right away.
Try something like :
string line = Console.ReadLine();
int value;
if (int.TryParse(line, out value))
{
// this is an int
// do you minimum number check here
}
else
{
// this is not an int
}
Simply call Readline() and loop with Int.TryParse until the user inputs a valid number :)
int X;
String Result = Console.ReadLine();
while(!Int32.TryParse(Result, out X))
{
Console.WriteLine("Not a valid number, try again.");
Result = Console.ReadLine();
}
Hope that helps
To get the console to filter out alphabetical keystrokes you have to take over input parsing. The Console.ReadKey() method is fundamental to this, it lets you sniff the pressed key. Here's a sample implementation:
static string ReadNumber() {
var buf = new StringBuilder();
for (; ; ) {
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && buf.Length > 0) {
return buf.ToString() ;
}
else if (key.Key == ConsoleKey.Backspace && buf.Length > 0) {
buf.Remove(buf.Length-1, 1);
Console.Write("\b \b");
}
else if ("0123456789.-".Contains(key.KeyChar)) {
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else {
Console.Beep();
}
}
}
You could add, say, Decimal.TryParse() in the if() statement that detects the Enter key to verify that the entered string is still a valid number. That way you can reject input like "1-2".
Do not Convert the input from the user immediately. Put it in a string and use Int32.TryParse(...) to find out whether or not a number was entered. Like this:
int i;
string input = Console.ReadLine();
if(Int32.TryParse(input, out i))
{
// it is a number and it is stored in i
}
else
{
// it is not a number
}
Note that
if (a < b) {
if (a < c) {
is equivalent to
if (a < b && a < c) {
and that this latter form introduces less nesting and is more readable, particularly if your code grows more complex. Also, you should probably never use Convert.ToInt32 - it has a particularly ill-conceived and surprising corner case; and it's also less type-safe than int.Parse which is the superior choice where possible - or int.TryParse when you're unsure whether the string is valid. Basically, avoid Convert.... wherever possible.
string Temp;
int tempInt,a;
bool result=false;
while ( result == false )
{
Console.Write ("\n Enter A Number : ");
Temp = Console.ReadLine ();
result = int.TryParse (Temp, out tempInt);
if ( result == false )
{
Console.Write ("\n Please Enter Numbers Only.");
}
else
{
a=tempInt;
break;
}
}
My preferred solution would be:
static void Main()
{
Console.WriteLine(
(
from line in Generate(()=>Console.ReadLine()).Take(3)
let val = ParseAsInt(line)
where val.HasValue
select val.Value
).Min()
);
}
static IEnumerable<T> Generate<T>(Func<T> generator) {
while(true) yield return generator();
}
static int? ParseAsInt(string str) {
int retval;
return int.TryParse(str,out retval) ? retval : default(int?);
}
Of course, depending on the specification (should invalid number be retried?), it may need to be tweaked.
Double/Float:
I'm just extending #Hans Passant answer (Taking care of DecimalSeparator and "-"):
static double ReadNumber()
{
var buf = new StringBuilder();
for (; ; )
{
var key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter && buf.Length > 0)
{
Console.WriteLine();
return Convert.ToDouble(buf.ToString());
}
else if (key.Key == ConsoleKey.Backspace && buf.Length > 0)
{
buf.Remove(buf.Length - 1, 1);
Console.Write("\b \b");
}
else if (System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator.Contains(key.KeyChar) && buf.ToString().IndexOf(System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator) == -1)
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else if ("-".Contains(key.KeyChar) && buf.ToString().IndexOf("-") == -1 && buf.ToString() == "")
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else if ("0123456789".Contains(key.KeyChar))
{
buf.Append(key.KeyChar);
Console.Write(key.KeyChar);
}
else
{
Console.Beep();
}
}
}
var getInput=Console.ReadLine();
int option;
//validating input
while(!int.TryParse(getInput, out option))
{
Console.WriteLine("Incorrect input type. Please try again");
getInput=Console.ReadLine();
}
Try This Simple
try
{
string x= "aaa";
Convert.ToInt16(x);
//if success is integer not go to catch
}
catch
{
//if not integer
return;
}