c# Console.WriteLine(); - 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()}");

Related

C# How set a non-numeric value to 0

I have to write a code that will ask for 3 integers values and find the greatest one. However, if the user enters a non numeric value this must have the value of zero. So far i wrote this
int a, b, c;
Console.WriteLine("Enter value 1:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value 2:");
b = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter value 3:");
c = Convert.ToInt32(Console.ReadLine());
if (a > b && a > c)
{
Console.WriteLine("The greatest value is: {0}", a);
}
if (b > a && b > c)
{
Console.WriteLine("The greatest value is: {0}", b);
}
if (c > a && c > b)
{
Console.WriteLine("The greatest value is: {0}", c);
}
This code works only with numbers.
My problem is that i can't make a non numeric input have the value of zero.
I tried using string instead of int, so there is no error but i can not make use ">" with strings in the if statements and i also tried using as default, because when is default so it is zero.
Thank you
You can just replace:
x = Convert.ToInt32(Console.ReadLine());
With...
int.TryParse(Console.ReadLine(), out int x);
If the input can't be parsed, x will end up being 0.
I think you can create a function that does the try catch, in this way you print a message saying that the input was not a number.
static int Check(string input)
{
int result;
try
{
result = Convert.ToInt32(input);
}
catch (FormatException e)
{
Console.WriteLine("Input not integer, the value assigned is 0");
result = 0;
}
return result;
}
For implementing you just call:
a = Check(Console.ReadLine());

Simple validation

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");
}
}

No overload method 'conversationOutput' takes '2' arguments

Hi I'm having trouble with an error "No overload method 'conversationOutput' takes '2' arguments" please help. I'm having a little trouble understanding method calling, and calling variables from main().
class MainClass
{
static void Main ()
{
string selection;
double values;
selection = userChoice();
values = userInput(selection);
conversationOutput(selection, values);
}
static string userChoice ()
{
string choose;
Console.WriteLine("Welcome to the OHM's law calculator! \n \nWhat would you like to calcualte?");
Console.WriteLine("1. Voltage:");
Console.WriteLine("2. Current:");
Console.WriteLine("3. Resistance:");
do
{
choose = Console.ReadLine();
if (choose != "1" && choose != "2" && choose != "3")
{
Console.WriteLine("Please only select '1' for voltage, '2' for current, '3' resistance");
}
} while (choose != "1" && choose != "2" && choose != "3");
switch (choose)
{
case "1":
Console.Write("You have choose to calculate Voltage.\n");
break;
case "2":
Console.Write("You have choose to calculate Current.\n");
break;
case "3":
Console.WriteLine("You have choose to calculate Resistance.\n");
break;
}
return choose;
}
static double userInput (string choose)
{
double voltageD = 0.0;
double currentD = 0.0;
double resistanceD = 0.0;
string current;
string voltage;
string resistance;
bool ok = true;
do if (choose != "1")
{
do
{
Console.WriteLine("Please enter your value for Voltage (volts)...");
voltage = Console.ReadLine();
ok = double.TryParse(voltage, out voltageD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (voltageD < 0)
{
Console.WriteLine("Please select a number larger than the lower limit of 0 volts");
}
} while (voltageD < 0);
do if (choose != "2")
{
do
{
Console.WriteLine("Please enter your value for Current (amp)...");
current = Console.ReadLine();
ok = double.TryParse(current, out currentD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (currentD < 0.01)
{
Console.WriteLine("Please select a number larger than the lower limit of 0.01 amp");
}
} while (currentD < 0.01);
do if (choose != "3")
{
do
{
Console.WriteLine("Please enter your value for Resistance (ohm)...");
resistance = Console.ReadLine();
ok = double.TryParse(resistance, out resistanceD);
if (!ok)
{
Console.WriteLine("Please Enter a NUMERICALE VALUE ONLY");
}
} while (!ok);
if (resistanceD < 10)
{
Console.WriteLine("Please select a number larger than the lower limit of 10 ohm");
}
} while (resistanceD < 10);
return 0;
}
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
{
/* v = i*r */
double output = 0.0;
string units = "";
if (choose == "1")
{
output = (currentD) * (resistanceD);
units = "Volts";
}
if (choose == "2")
{
output = (voltageD) / (resistanceD);
units = "Amps";
}
if (choose == "3")
{
output = (voltageD) / (resistanceD);
units = "OHM";
}
Console.WriteLine("The calculated value is {0:F3} {1:F3}", output, units);
return 0;
}
}
The reason is you have a method
double conversationOutput (string choose, double currentD, double voltageD, double resistanceD)
which has 4 parameters and you are passing only 2 parameters to the method.
define the missing parameters as optional
static double conversationOutput (string choose, double currentD, double voltageD =0, double resistanceD =1)
As per the method definition, conversationOutput expects four parameters.
static double conversationOutput (string choose, double currentD, double voltageD, double resistanceD) {}
But you are calling it by passing just two parameters.
conversationOutput(selection, values);
That's why you are getting such error.
It will work if you call the conversationOutput method by passing four parameters.

How do I only allow number input into my C# Console Application?

Console.WriteLine("Enter the cost of the item");
string input = Console.ReadLine();
double price = Convert.ToDouble(input);
Hello, I want the keyboard buttons, A-Z, brackets, question mark, etc to be disabled. I want it so if you type it in, it will not show up in the Console. I only want the numbers 1-9 to show up. This is in C# Console application. Thanks for the help!
try this code snippet
string _val = "";
Console.Write("Enter your value: ");
ConsoleKeyInfo key;
do
{
key = Console.ReadKey(true);
if (key.Key != ConsoleKey.Backspace)
{
double val = 0;
bool _x = double.TryParse(key.KeyChar.ToString(), out val);
if (_x)
{
_val += key.KeyChar;
Console.Write(key.KeyChar);
}
}
else
{
if (key.Key == ConsoleKey.Backspace && _val.Length > 0)
{
_val = _val.Substring(0, (_val.Length - 1));
Console.Write("\b \b");
}
}
}
// Stops Receving Keys Once Enter is Pressed
while (key.Key != ConsoleKey.Enter);
Console.WriteLine();
Console.WriteLine("The Value You entered is : " + _val);
Console.ReadKey();
This MSDN article explains how to read characters one at a time in a console window. Test each character as it is input with the Char.IsNumber() method, and reject those characters that fail the test.
In a while, I got a solution really short:
double number;
Console.Write("Enter the cost of the item: ");
while (!double.TryParse(Console.ReadLine(), out number))
{
Console.Write("This is not valid input. Please enter an integer value: ");
}
Console.Write("The item cost is: {0}", number);
See you!
Here is one approach. It's probably overkill if you're just starting out in C#, since it uses some more advanced aspects of the language. In any case, I hope you find it interesting.
It has some nice features:
The ReadKeys method takes an arbitrary function for testing whether the string so far is valid. This makes it easy to reuse whenever you want filtered input from the keyboard (e.g. letters or numbers but no punctuation).
It should handle anything you throw at it that can be interpreted as a double, e.g. "-123.4E77".
However, unlike John Woo's answer it doesn't handle backspaces.
Here is the code:
using System;
public static class ConsoleExtensions
{
public static void Main()
{
string entry = ConsoleExtensions.ReadKeys(
s => { StringToDouble(s) /* might throw */; return true; });
double result = StringToDouble(entry);
Console.WriteLine();
Console.WriteLine("Result was {0}", result);
}
public static double StringToDouble(string s)
{
try
{
return double.Parse(s);
}
catch (FormatException)
{
// handle trailing E and +/- signs
return double.Parse(s + '0');
}
// anything else will be thrown as an exception
}
public static string ReadKeys(Predicate<string> check)
{
string valid = string.Empty;
while (true)
{
ConsoleKeyInfo key = Console.ReadKey(true);
if (key.Key == ConsoleKey.Enter)
{
return valid;
}
bool isValid = false;
char keyChar = key.KeyChar;
string candidate = valid + keyChar;
try
{
isValid = check(candidate);
}
catch (Exception)
{
// if this raises any sort of exception then the key wasn't valid
// one of the rare cases when catching Exception is reasonable
// (since we really don't care what type it was)
}
if (isValid)
{
Console.Write(keyChar);
valid = candidate;
}
}
}
}
You also could implement an IsStringOrDouble function that returns false instead of throwing an exception, but I leave that as an exercise.
Another way this could be extended would be for ReadKeys to take two Predicate<string> parameters: one to determine whether the substring represented the start of a valid entry and one the second to say whether it was complete. In that way we could allow keypresses to contribute, but disallow the Enter key until entry was complete. This would be useful for things like password entry where you want to ensure a certain strength, or for "yes"/"no" entry.
This code will allow you to:
Write only one dot (because numbers can have only one decimal separator);
One minus at the begining;
One zero at the begining.
It means that you not be able to write something like: "00000.5" or "0000...-5".
class Program
{
static string backValue = "";
static double value;
static ConsoleKeyInfo inputKey;
static void Main(string[] args)
{
Console.Title = "";
Console.Write("Enter your value: ");
do
{
inputKey = Console.ReadKey(true);
if (char.IsDigit(inputKey.KeyChar))
{
if (inputKey.KeyChar == '0')
{
if (!backValue.StartsWith("0") || backValue.Contains('.'))
Write();
}
else
Write();
}
if (inputKey.KeyChar == '-' && backValue.Length == 0 ||
inputKey.KeyChar == '.' && !backValue.Contains(inputKey.KeyChar) &&
backValue.Length > 0)
Write();
if (inputKey.Key == ConsoleKey.Backspace && backValue.Length > 0)
{
backValue = backValue.Substring(0, backValue.Length - 1);
Console.Write("\b \b");
}
} while (inputKey.Key != ConsoleKey.Enter); //Loop until Enter key not pressed
if (double.TryParse(backValue, out value))
Console.Write("\n{0}^2 = {1}", value, Math.Pow(value, 2));
Console.ReadKey();
}
static void Write()
{
backValue += inputKey.KeyChar;
Console.Write(inputKey.KeyChar);
}
}
You can do it with a single line code as follows:
int n;
Console.WriteLine("Enter a number: ");
while (!int.TryParse(Console.ReadLine(), out n)) Console.WriteLine("Integers only allowed."); // This line will do the trick
Console.WriteLine($"The number is {n}");
You can change int into double in case you wanted to allow double instead of integers and so on.
string input;
double price;
bool result = false;
while ( result == false )
{
Console.Write ("\n Enter the cost of the item : ");
input = Console.ReadLine ();
result = double.TryParse (input, out price);
if ( result == false )
{
Console.Write ("\n Please Enter Numbers Only.");
}
else
{
Console.Write ("\n cost of the item : {0} \n ", price);
break;
}
}

How can I validate console input as integers?

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;
}

Categories