Pass Function To Main Method Args Cmd Prompt - c#

i am trying to pass a add or subtract function to main method args. in cmd if i run the program with 1 it should display the AddFunction and if i press it with 2 it should display the minusFunction. this is what i have done so far im a little stuck
using System;
namespace addSubtractProject
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Welcome to Add and Subtract Program!");
Console.WriteLine("============================");
if (args.Length > 0)
{
if (args[0] == "1")
{
Console.WriteLine("You are using the AddFunction");
(AddTwo);
}
else if (args[0] == "2")
{
Console.WriteLine("You are using the subtractFunction");
(subtractTwo);
Console.ReadLine();
}
int x = 10, y = 5;
int z = AddTwo(x, y); // function that returns a value
int i = subtractTwo(x, y);
}
}
//function Add Two Numbers
static int AddTwo(int a, int b)
{
return (a + b);
}
//function Minus Two Numbers
static int subtractTwo(int a, int b)
{
return (a - b);
}
}
}

With little modification, you can do this:
if (args.Length > 0)
{
int x = 10, y = 5;
if (args[0] == "1")
{
Console.WriteLine("You are using the AddFunction");
Console.WriteLine(string.Format("Result = {0}", AddTwo(x,y) ));
}
else if (args[0] == "2")
{
Console.WriteLine("You are using the subtractFunction");
Console.WriteLine(string.Format("Result = {0}", subtractTwo(x,y) ));
}
}
Hopefully, this can give you some ideas. The code can be improved even further and I'll leave this for you to try by yourself.

Related

How do I set a value in one method and then return that value to another method?

I need some help. If I understand this right, the value of "int F" gets sent to "FtoC" converted and then returned to the MenuSelect1 method.
Now I want to return or save the value "int C" has after its been converted to the MenuSelect2 method? I have tried everything I can think of, but I just get errors. (I have reset the code to original state now where MenuSelect1 and 2 är void). Whats an easy way to solve this? Thank you.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class SecondClass {
public static int FtoC(int fahrenheit)
{
int C = ((fahrenheit - 32) * 5) / 9;
return C;
}
public static void MenuSelect1()
{
while (true)
{
int F = 0;
Console.Write("\nType how many degrees Fahrenheit you want: ");
try
{
F = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("ERROR!");
Console.ForegroundColor = ConsoleColor.White;
}
int C = SecondClass.FtoC(F);
if (C < 80 || C > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(C + "°C is perfect. Start the sauna and enjoy!");
break;
}
}
Console.ReadKey();
}
public static void MenuSelect2()
{
Console.WriteLine("Starting Sauna. Wait for it to reach desired temperature...");
Console.Write("Temperature: {0}");
Console.ReadKey();
}
}
You could also save the value of C as a property / field in your class. Here is an example of saving it as a field called _celcius:
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
public static class SecondClass {
private static int _celcius = 0; // <--- Your field
public static int FtoC(int fahrenheit)
{
int C = ((fahrenheit - 32) * 5) / 9;
return C;
}
public static void MenuSelect1()
{
while (true)
{
int F = 0;
Console.Write("\nType how many degrees Fahrenheit you want: ");
try
{
F = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("ERROR!");
Console.ForegroundColor = ConsoleColor.White;
}
_celcius = SecondClass.FtoC(F); // <--- Assign field here
if (_celcius < 80 || _celcius > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(_celcius + "°C is perfect. Start the sauna and enjoy!");
break;
}
}
Console.ReadKey();
}
public static void MenuSelect2()
{
Console.WriteLine("Starting Sauna. Wait for it to reach desired temperature...");
Console.Write("Temperature: {0}", _celcius); // <--- Use your field here
Console.ReadKey();
}
}```
You either call the MenuSelect2() directly from the MenuSelect1()
public static void MenuSelect1()
{
while (true)
{
int F = 0;
Console.Write("\nType how many degrees Fahrenheit you want: ");
try
{
F = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("ERROR!");
Console.ForegroundColor = ConsoleColor.White;
}
int C = SecondClass.FtoC(F);
if (C < 80 || C > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(C + "°C is perfect. Start the sauna and enjoy!");
// here
MenuSelect2(C);
break;
}
}
Console.ReadKey();
}
public static void MenuSelect2(int C)
{
Console.WriteLine("Starting Sauna. Wait for it to reach desired temperature...");
Console.Write($"Temperature: {C}"); // <- notice the $ for interpolated strings.
}
Or return the value from the MainSelect1() to the caller which calls the MainSelect2() method.
public static void Main()
{
// get the temperature
int C = MenuSelect1();
// pass it to the other method.
MenuSelect2(C);
Console.ReadKey();
}
public static int MenuSelect1() // <- change the signature (return int)
{
while (true)
{
int F = 0;
Console.Write("\nType how many degrees Fahrenheit you want: ");
try
{
F = Convert.ToInt32(Console.ReadLine());
}
catch (Exception e)
{
Console.ForegroundColor = ConsoleColor.DarkRed;
Console.WriteLine("ERROR!");
Console.ForegroundColor = ConsoleColor.White;
}
int C = SecondClass.FtoC(F);
if (C < 80 || C > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(C + "°C is perfect. Start the sauna and enjoy!");
return C; // return the value to the caller.
}
}
}
public static void MenuSelect2(int C)
{
Console.WriteLine("Starting Sauna. Wait for it to reach desired temperature...");
Console.Write($"Temperature: {C}"); // <- notice the $ for interpolated strings.
}
I rather use the second suggestion, because this way the MenuSelect1() isn't tightcoupled to MenuSelect2() and can be reused for other purposes.
The problem at this point is that the variable C is instantiated and stored inside the method MenuSelect1(), what you should do is create a class variable like int fahrenheitValue and then inside the menuSelect1 method use this.fahrenheitValue = C so the value is stored inside the class variable and then you can access it from everywhere
All the variables that are defined in MenuSelect1() will NOT be visible as soon as the method ends.
You can define a static property in your "SecondClass"
private static int degreesCelsius;
Then you can set this property in
if (C < 80 || C > 87)
{
Console.WriteLine("Try a different temperature.");
}
else
{
Console.WriteLine(C + "°C is perfect. Start the sauna and enjoy!");
degreesCelsius = C;
break;
}
In your MenuSelect2() method you can use it.
Console.Write("Temperature: {0}", degreesCelsius);

methods program not working of guessing a number

I'm having issues creating a program that is a number guessing program. I think I have the written part right but possibly not the order of it? I have to use multiple methods such as a method for number generator of the number that is supposed to be guessed, a method for collecting the guess input, and method for checking the guess to see if it's right. I've literally have tried just about everything for days but all I get is rather a repeat of, "Enter the number: " even if its right, although it's supposed to repeat if it's too high or low. Or sometimes the console won't print anything. what is wrong? Here is the code:
using System;
namespace GuessTheNumber
{
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
return random.Next(1, 21);
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if(guess > secretNumber)
{
return "Too high!";
}
else if (guess < secretNumber)
{
return "Too low!";
}
else
{
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
while (InputGetter() != secretNumber)
{
InputGetter();
GuessChecker(InputGetter(), secretNumber);
}
if (GuessChecker(InputGetter(), secretNumber) == ("Correct!"))
{
Console.WriteLine("Would you like to play again?");
String input = Console.ReadLine();
if (GuessChecker(InputGetter(), secretNumber) == ("Yes"))
{
secretNumber = RandomNumberGenerator();
}
else if (GuessChecker(InputGetter(), secretNumber) == ("No"))
{
break;
}
}
}
}
}
}
You are invoking InputGetter() multiple times and your logic is incorrect.
It has nothing to do with Random instance being used.
I have quickly modified your code and it should work now as follows:
New number is generated, if you enter low/high message is displayed, if you enter correct number you are presented with the Would you like to try again message.
EDIT: I did not want to change original code much,In general Comparing strings is bad, you should not use it. Creating enum like and comparing would be much better
class Program
{
public static int RandomNumberGenerator()
{
Random random = new Random();
var generatedNumber = random.Next(1, 21);
Console.WriteLine($"New Number generated! {generatedNumber}");
return generatedNumber;
}
public static int InputGetter()
{
Console.Write("Enter in a number: ");
int guess = Convert.ToInt32(Console.ReadLine());
return guess;
}
public static String GuessChecker(int guess, int secretNumber)
{
if (guess > secretNumber)
{
Console.WriteLine("Too High");
return "Too high!";
}
else if (guess < secretNumber)
{
Console.WriteLine("Too low!");
return "Too low!";
}
else
{
Console.WriteLine("Correct");
return "Correct";
}
}
static void Main(string[] args)
{
int secretNumber = 10;
Console.WriteLine("" + secretNumber);
while (true)
{
int enteredNumber = 0;
do
{
enteredNumber = InputGetter();
} while (GuessChecker(enteredNumber, secretNumber)!="Correct");
Console.WriteLine("Would you like to play again?[Yes/No]");
String input = Console.ReadLine();
if (input=="Yes")
{
secretNumber = RandomNumberGenerator();
}
else
{
break;
}
}
}
}

C# Trouble wiith Blackjack Game

I'm having trouble with the counter variable. Every time I leave each method, count is re-initialized to 0. I haven't completed the Stay() method the Hit() method is killing. After every Hit I need to display all of the user's cards. I do not know how to do this. There has to be a more efficient way. I think all my problems arise from the problem with the Count variable.
Thanks for any help.
Below is my main class. Below that is my Deck class.
I left out the Card, Suit and Rank class.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlkJack
{
class Program
{
static void Main(string[] args)
{
string name;
int Chips = 500;
int Wage;
int count = 0;
string HS;
Card pCard1, dCard1, pCard2, dCard2;
int playerHand, dealerHand;
//int chipsWon;
Console.WriteLine("Welcome to Johnny's BlackJack!");
Console.WriteLine("You are given $500 to play with.");
Console.WriteLine("Table Limit is $250 per hand. <Enter a 0 to quit>");
name = GetName("Enter name: ");
Console.WriteLine("Hello {0}, you are ${1} ahead.", name, Chips);
Wage = getWager("What is your wager?: ", 1, 250, "?Value must be an integer.", "Max bet is 250!");
Deck d = new Deck();
startingHand(count, d, out pCard1, out dCard1, out pCard2, out dCard2, out playerHand, out dealerHand);
Console.WriteLine("Your hand: {0}, {1} <{2}> ", pCard1, pCard2, playerHand);
Console.WriteLine("<Dealer's show card is {0}>", dCard1);
count = count + 4;
HS = HitorStay("Do you want to <H>it or <S>tay?: ", count, playerHand, d);
while (HS == "H" || HS == "HIT")
{
HS = HitorStay("Do you want to <H>it or <S>tay?: ", count, playerHand, d);
Console.WriteLine("Your cards: {0} {1} <{2}>", pCard1, pCard2, playerHand);
//Console.WriteLine("{0}", count);
}
}
static string GetString(string prompt, string[] valid, string error)
{
string response;
bool OK = false;
do
{
Console.Write(prompt);
response = Console.ReadLine().ToUpper();
foreach (string s in valid) if (response == s) OK = true;
if (!OK) Console.WriteLine(error);
}
while (!OK);
return response;
}
static string GetName(string prompt)
{
string response;
Console.Write(prompt);
response = Console.ReadLine();
while (response == "0")
{
Environment.Exit(0);
}
return response;
}
static bool GetYesNo(string prompt)
{
string[] valid = { "YES", "Y", "NO", "N" };
string ans = GetString(prompt, valid, "Invalid response. Please reenter.");
return (ans == "YES" || ans == "Y");
}
static int getWager(string prompt, int low, int high, string errorInt, string errorRange)
{
int Wager;
string userInput;
bool OKInt = false, OKRange = false;
do
{
Console.Write(prompt);
userInput = Console.ReadLine();
OKInt = Int32.TryParse(userInput, out Wager);
if (OKInt)
{
OKRange = low <= Wager && Wager <= high;
if (!OKRange) Console.WriteLine(errorRange);
}
else
Console.WriteLine(errorInt);
}
while (!OKInt || !OKRange);
return Wager;
}
public static int startingHand(int count, Deck d, out Card pCard1, out Card dCard1, out Card pCard2, out Card dCard2, out int playerHand, out int dealerHand)
{
playerHand = 0; dealerHand = 0;
if (count == 0 || count >= 42) d.Shuffle();
for (int i = 0; i < 52; i++)
Console.Write("{0},", d.GetCard(i));
pCard1 = d.GetCard(count);
count++;
dCard1 = d.GetCard(count);
count++;
pCard2 = d.GetCard(count);
count++;
dCard2 = d.GetCard(count);
count++;
playerHand = pCard1.GetValue() + pCard2.GetValue();
dealerHand = dCard1.GetValue() + dCard2.GetValue();
return count;
}
static string HitorStay(string prompt, int count, int playerHand, Deck d)
{
string[] valid = { "HIT", "H", "STAY", "S" };
string HS = GetString(prompt, valid, "?Invalid Response. (H)it or (S)tay?");
if (HS == "HIT" || HS == "H")
{
Hit(count, playerHand, d);
}
//else if (HS == "STAY" || HS == "S")
//{
//Stay(count, playerHand, dealerHand, out chipStay);
//}
else Environment.Exit(0);
return HS;
}
public static int Hit(int count, int playerHand, Deck d)
{
count += 1;
playerHand += d.GetCard(count).GetValue();
return playerHand;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BlkJack
{
class Deck
{
private Card[] cards = new Card[52];
public Deck()
{
for (int suitVal=0; suitVal<4; suitVal++)
{
for (int rankVal = 0; rankVal < 13; rankVal++)
{
cards[suitVal * 13 + rankVal] =
new Card((Suit)suitVal, (Rank)(rankVal));
cards[suitVal * 13 + rankVal].SetValue(rankVal);
if (rankVal > 9) cards[suitVal * 13 + rankVal].SetValue(10);
if (rankVal == 1) cards[suitVal * 13 + rankVal].SetValue(11);
if (rankVal == 0) cards[suitVal * 13 + rankVal].SetValue(10);
}
}
}
public Card GetCard(int cardNum)
{
return cards[cardNum];
}
public void Shuffle()
{
Card[] newDeck = new Card[52]; // cards randomly assigned to locs in newDeck
bool[] assigned = new bool[52]; // keep track of what locs used in newDeck
int seed = 0;
Console.Write("Enter seed: ");
seed = Convert.ToInt32(Console.ReadLine()); // yes, stupid user can break
Random rGen = new Random(seed);
for (int i=0; i<52; i++)
{
int destCard = 0; // where card is going to be put
bool foundCard = false;
while (foundCard == false)
{
destCard = rGen.Next(52);
if (assigned[destCard] == false)
foundCard = true;
}
assigned[destCard] = true;
newDeck[destCard] = cards[i];
}
newDeck.CopyTo(cards, 0); //.CopyTo(destination, start index)
}
}
}
Look at this code
public static int Hit(int count, int playerHand, Deck d)
{
count += 1;
You are passing in a copy of count and incrementing that copy. The original value you passed in is never affected. Straightforward fixes include
Pass count by reference ref int count.
Make count a static class field rather than a local variable in Main()
A much better way would be to encapsulate your logic in a class and make count a field or property of that class, so that class methods can see and change it.

Returning to Main when using an interface in C#

So I've created a blackjack game using an interface whose entry point is "PlayGames()". However, once the game is finished, I want to give the option to the user to go back to the main menu, which is in Main(). Is there a way to call main so that the user can go back to the main menu? Simply calling Main() does not work.
Here's what I've got:
public void PlayGames ()
{
String replay = "";
var a = PlayBlackjack (r, replay);
Console.WriteLine ();
while (a == "yes") {
a = PlayBlackjack (r, replay);
if (a == "no") {
Console.WriteLine ("Okay, goodbye!");
return;
}
}
if (a == "z") {
Main ();
}
}
The variable a is the string user-entered string that determines if the game closes, or continues to play. If the user enters that they want to go back to the main menu, the letter "z" is assigned to a, which will lead them back to the main menu.
Here's what Main() looks like, including class information. The error message that comes up says "Main does not exist in the current context":
using System;
using System.IO;
using System.Collections.Generic;
namespace IntroCS
{
public class PlayCasino
{
private static Random rand = new Random();
private static List<Casino> games;
public static void Main()
{
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
int n = UIF.PromptInt ("Please enter an integer to choose your game: ");
games = new List<Casino> ();
games.Add (new HelpMenu ());
games.Add (new BlackJack ());
games.Add (new QuarterGame ());
if (n == 0) {
Console.WriteLine ("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
}
if (n == 1) {
Console.Clear ();
Console.WriteLine ("Playing Blackjack!" + "\n");
games [0].PlayGames (); //ensures user will get blackjack
}
if (n == 2) {
Console.Clear ();
Console.WriteLine ("Playing the Quarter Game!" + "\n");
games [1].PlayGames (); //ensures user will get quartergame
}
while (n != 0 && n != 1 && n != 2) {
Console.WriteLine ("Try another game!");
n = UIF.PromptInt ("Please enter an integer: ");
}
}
}
}
I would recommend you to put displaying menu & getting input into a function. Just to make it easy to comprehend. Also in your list of games, maybe you want to keep track of game history? if so you need to keep adding a new one like so:
using System;
using System.IO;
using System.Collections.Generic;
using ConsoleApplication8;
namespace IntroCS
{
public class PlayCasino
{
private static Random rand = new Random();
private static List<Casino> games = new List<Casino>();
private static const int INVALID_CODE = -111;
private static const int EXIT_CODE = 4;
public static void Main()
{
int choosen = INVALID_CODE;
while (choosen != EXIT_CODE)
{
switch (choosen)
{
case INVALID_CODE:
choosen = DisplayMenu();
break;
case 0:
displayHelp();
choosen = INVALID_CODE;
break;
case 1:
games.Add(new BlackJack());
games[games.Count-1].PlayGames();
break;
case 2:
games.Add(new QuarterGame());
games[games.Count-1].PlayGames();
break;
default:
DisplayMenu();
break;
}
}
}
private static void displayHelp()
{
Console.WriteLine("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
}
private static int DisplayMenu()
{
Console.WriteLine("MAIN MENU");
Console.WriteLine("(0 for help)");
Console.WriteLine("(1 for blackjack)");
Console.WriteLine("(2 for Quarter Game)");
Console.WriteLine("Please enter an integer to choose your game: ");
string input = Console.ReadLine();
int number;
if (Int32.TryParse(input, out number))
return number;
else
{
Console.WriteLine("Please Try an Integer");
return INVALID_CODE;
}
}
}
}
Your while is repeating the wrong stuff:
public static void Main()
{
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
int n = UIF.PromptInt ("Please enter an integer to choose your game: ");
games = new List<Casino> ();
games.Add (new HelpMenu ());
games.Add (new BlackJack ());
games.Add (new QuarterGame ());
while (n != 0 && n != 1 && n != 2) {
if (n == 0) {
Console.WriteLine ("Accessing the Help Menu!" + "\n");// this is where we will print directions/ help menus
Console.WriteLine ("MAIN MENU");
Console.WriteLine ("(0 for help)");
Console.WriteLine ("(1 for blackjack)");
Console.WriteLine ("(2 for Quarter Game)");
}
if (n == 1) {
Console.Clear ();
Console.WriteLine ("Playing Blackjack!" + "\n");
games [0].PlayGames (); //ensures user will get blackjack
}
if (n == 2) {
Console.Clear ();
Console.WriteLine ("Playing the Quarter Game!" + "\n");
games [1].PlayGames (); //ensures user will get quartergame
}
Console.WriteLine ("Try another game!");
n = UIF.PromptInt ("Please enter an integer: ");
}
}
Notice you never left the "Main" function, so in your "PlayGames" function you can just go ahead and return:
public void PlayGames ()
{
String replay = "";
var a = PlayBlackjack (r, replay);
Console.WriteLine ();
while (a == "yes") {
a = PlayBlackjack (r, replay);
if (a == "no") {
Console.WriteLine ("Okay, goodbye!");
return;
}
}
//Do nothing, the while in Main function will already take us back to the menu
}

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