Writing an executable function in C# - c#

I'm really new to all of this. I need to write an exe application in C#. What i need to do is to be able to pass values through the console into a function. But I'm unsure as to how I can store the values that are entered through the console...
I know we can use Read() to read what has been entered but, when I'm dealing with multiple values how do i do this?
Any help will be greatly appreciated!! Thanks in advance

You start with choosing the Console Application template (in New Project)
And then, in the Main function, you can read a line at a time with
string line = Console.ReadLine();
This probably shifts your question to : How do I get values from a string?
If you have a single int at a time, it is
int x = int.Parse(line);

Are you referring to passing command line parameters to a console application? If so, there is a string array parameter (e.g. args) that holds them. See this code.
static void Main(string[] args)
{
}
You can also use Environment.GetCommandLineArgs.

Hmm I think he is wondering how to repeatitly read some value and pass it to a function.
For that you can use a simple while loop.
string data = Console.ReadLine();
do {
dummyFunction(data);
data = Console.ReadLine();
} while (data != "");

You want to programmatically compile text into code? If so you should read this KB entry from Microsoft. How to programmatically compile code using C# compiler
Or if you want to get input from the user in the console, you should use Console.ReadLine().
Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.Write("Enter your age: ");
int age = int.Parse(Console.ReadLine());
Console.Write("Hello {0}, you are {1} years old.", name, age);

You can basically do a parsing work manually. For example, if the input is a name follows by age.
Natthawut 22
You can use Console.ReadLine() to get the string "Nattawut 22". And then use String.Split(' '); to get an array of {"Natthawut","22"}. Then convert the second element to integer using Convert.ToInt32(val);
I believe there must be a better way to do this but this is how I usually do it :)

int year, month, day;
Console.WriteLine("Please enter your birth year : ");
year = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter your birth month : ");
month = int.Parse(Console.ReadLine());
Console.WriteLine("Please enter your birth day : ");
day = int.Parse(Console.ReadLine());
Console.Write("You are ");
Console.Write(CalculateAge(year, month, day));
Console.Write(" years old.");
An alternative way is this:
Console.WriteLine("Please enter your birthday in the format YY-MM-DD : ");
string line = Console.ReadLine();
string[] parts = line.Split(new char[] { '-' });
int age = CalculateAge(parts[0],parts[1],parts[2]);
Console.WriteLine("You are {0} years old.", age);
And -PLEASE- do some input checking.

Related

How to remove a series of individual letters from a string?

Messing around with C# logic, trying to build a program where the user inputs a string, and then has the option to decide which letter is removed from said string.
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
Console.WriteLine("please enter letters you would like removed");
char removedLetters = Convert.ToChar(Console.ReadLine());
foreach (char letter in input)
{
Console.WriteLine(input.Replace(removedLetters,' ').ToLower());
}
This works, but not entirely. I will get rid of characters, but only when written in a specific way that corresponds with the original input.
e.g helloworld -> remove l = he owor d
but helloworld -> remove elo = failure.
Can someone share some knowledge? Really trying to get better at logic, happy i got this far just need bit of guidance.
Cheers,
Andy
Expanding on Jasen's comment from earlier something like this ...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
List<char> input_array = input.ToList();
Console.WriteLine("please enter letters you would like removed");
string removedLetters = Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
for (int k = 0; k < remove_array.Count(); k++)
{ input_array.RemoveAll(r=>r== remove_array[k]); }
Console.WriteLine(new string(input_array.ToArray()));
Again, using Linq, in this case RemoveAll, to automate the heavy lifting. I have not tested how efficient these are, they are quick and simple solutions not necessarily the most efficient.
Not sure how you want to handle duplicates but C# has an Except operator that works on Arrays. So convert both strings to an array and something like this should work...
Console.WriteLine("Please enter a string of letters");
string input = Console.ReadLine();
char[] input_array = input.ToArray();
Console.WriteLine("please enter letters you would like removed");
string removedLetters =Console.ReadLine();
char[] remove_array = removedLetters.ToArray();
char[] leftover_array = input_array.Except(remove_array).ToArray();
Console.WriteLine(new string(leftover_array));

Error message not being displayed; incorrect conversion

Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput = Convert.ToInt32(userInput);
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
Can someone explain to me why my error message isn't showing up, and why the int newUserInput line is getting the error that it's not formatted correctly?
Try this:
Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput;
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}
Just do your work here int.TryParse(userInput, out newUserInput), not converting it before TryParse
It totally depends on what are you sending in with Console.ReadLine()
Also, see following:
Convert.ToInt32 will throw FormatException if input is not correct for Int32. Refer Convert.Int32(MSDN)
Also it looks like you are overwriting the Convert.Int32 again with TryParse. You actually dont need Convert.Int32
Console.Write("Enter a limit to the prime numbers you want displayed: ");
userInput = Console.ReadLine();
int newUserInput; //dont assign anything
if (!int.TryParse(userInput, out newUserInput))
{
Console.WriteLine("\nThe value entered must be a whole number. Please try again: ");
}

Characters not returning

How to fix the errors with characters in C# Employee class I am making. I know how to handle string, int, and double. The char.Parse doesn't cooperate.
public static string AskForLastName()
{
string inValue;
Console.Write("Enter last name: ");
inValue = Console.ReadLine();
return inValue; //works fine
}
public static char AskForGender()
{
char inValue;
Console.Write("Enter gender: ");
inValue = Console.ReadLine();//error here for some reason
return (char.Parse(inValue));//error here for some reason
}
public static int AskForNoDependendents()
{
string inValue;
Console.Write("Enter the dependents: ");
inValue = Console.ReadLine();
return (int.Parse(inValue));//works fine
}
public static double AskForAnnualSalary()
{
string inValue;
Console.Write("Enter annual salary: ");
inValue = Console.ReadLine();
return (double.Parse(inValue));//works fine
}
Console.ReadLine() returns a string. You can't implicitly convert that to a character- what if someone enters "Male" or " M" (preceded by one or more spaces).
Your AskForGender method is going to need to be smarter about what input it accepts, and how it parses that input.
If you really need a character out of this (to satisfy the assignment, or whatever), then you need to figure out a way to get from all of the possible String inputs ("Male", "MALE", "Female", "Horse", "Dog", "4", etc.) to either:
An acceptable Character (presumably 'M' or 'F', but maybe others?)
or
An error condition, whereupon maybe you print a nice error message and ask them to re-enter?
Description
Console.ReadLine returns a string. You can use string[] to get the first character of your string. But you have to make sure that the user inserts at least one character.
Sample
public static char AskForGender()
{
while (true)
{
Console.Write("Enter gender (m/w): ");
string inValue = Console.ReadLine();
// check that the user inputs a character
if (!string.IsNullOrEmpty(inValue) && (inValue[0] == 'm' || inValue[0] == 'w'))
return inValue[0];
}
}
Update
My sample covers now that the user inputs m or w.
Update
It is homework so...
If your Teacher ask "But what happens if the user inputs a M instead of m? You should say "It asks the user again".
If your Teacher asks then "How to make it possible to accept M and m? You should say i can make it case insensitive.
Sample
You should use i can use .NET's .ToUpper() method.
.ToUpper() - Returns a copy of this string converted to uppercase.
public static char AskForGender()
{
while (true)
{
Console.Write("Enter gender (m/w): ");
string inValue = Console.ReadLine();
// check that the user inputs a character
if (!string.IsNullOrEmpty(inValue) && (inValue.ToUpper()[0] == 'M' || inValue.ToUpper()[0] == 'W'))
return inValue.ToUpper()[0]; // returns M or W
}
}
You're trying to pull a string into a char. Console.ReadLine() returns a string.
If you need specifically one character (Presumably M or F) consider making your inValue a string, trimming it (to ensure there are no leading spaces), and then returning inValue[0] (which should be a char)
Something like:
string inValue = Console.ReadLine();
inValue = inValue.Trim();
return inValue[0];
**Note- that's not the best way to do it, but it should make the idea fairly clear.
According to MSDN ReadLine returns a string - you can't assign a string to a char!

Unhandled Exception: System.FormatException: Input string was not in a correct format

I'm trying to get this small movie ratings program to work properly with everything going fine until I start prompting for the ratings that the reviewer would enter. It lets me rate both acting fine but as soon as I hit the enter button to rate music is will move down to a blank line instead of prompting for the next input. The only way I to get around this seems for me to enter the value twice.
thanks
Console.WriteLine("Rate the following out of 5");
Console.Write("Acting > ");
acting_rating = int.Parse(Console.ReadLine());
Console.Write("Music > ");
Console.ReadLine();
music_rating = int.Parse(Console.ReadLine());
Console.Write("Cinematography > ");
Console.ReadLine();
cinematography_rating = int.Parse(Console.ReadLine());
Console.Write("Plot > ");
Console.ReadLine();
plot_rating = int.Parse(Console.ReadLine());
Console.Write("Duration > ");
Console.ReadLine();
duration_rating = int.Parse(Console.ReadLine());
you call Console.ReadLine(); one time too often... just remove the Console.ReadLine(); between Console.Write and the int.Parse .
Although IF the user enters anthing wrong - like a word instead of a number - you will still get an exception... To handle that properly use a try catch block and/or TryParse.
Excluding Acting, you have always two Console.ReadLine(); i.e. :
Console.Write("Music > "); // write Music >
Console.ReadLine(); // read the user input (and throw it away)
music_rating = int.Parse(Console.ReadLine()); // read the user input again and parse it
Remove the single statement Console.ReadLine(); and should be ok.

C# program for months

i am strugling with an exercise. I am a beginer and dont know where to start. I am asked to create a console program that if you give it a number between 1 and 12 it must give you the corresponding month name and if you give it the name of the month it should give you the number of the month. Please help with the code. It should be done using an ARRAY. Thank you.
Depends on what you're learning, I guess... they may just be demonstrating a switch(intMonth) type thing, so:
switch(intMonth)
{
case 1:
return "January";
break;
case 2:
return "February";
break;
....
}
Or as mentioned, make use of DateTime...
There's many many ways to do it... I guess you need to select the right way... most efficient way... so, depends on your assignment.
Good luck.
Hopefully you will learn something from this code, because if it gets copied to a USB stick and givent to the teacher without even taking alook to it, I will be very mad, come to your home and do a mess! :)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int iMonth = -1;
// loop until iMonth is 0
while (iMonth != 0)
{
Console.WriteLine("Please insert a number from 1 to 12 and press enter. Enter 0 to exit.");
string sMonth = Console.ReadLine();
// try to get a number from the string
if (!int.TryParse(sMonth, out iMonth))
{
Console.WriteLine("You did not enter a number.");
iMonth = -1; // so we continue the loop
continue;
}
// exit the program
if (iMonth == 0) break;
// not a month
if (iMonth < 1 || iMonth > 12) {
Console.WriteLine("The number must be from 1 to 12.");
continue;
}
// get the name of the month in the language of the OS
string monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(iMonth);
Console.WriteLine("The name of the month is " + monthName);
}
}
}
}
If your teacher expects a custom provided name then you can use the switch statement in the last part:
switch (iMonth)
{
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
// add more
}
If he expects an array exercise then you can declare an array with all the strings and use that:
string[] monthNames = new string[] {
"January",
"February",
// add more
};
and use this to get the name:
Console.WriteLine(monthNames[iMonth]);
Do like that :
String to Int Month
Code :
Datetime.Parse(Monvalue + "/1/2011").ToString("MM")
Like :
Datetime.Parse("January/1/2011").ToString("MM")
Retrun :
01
Int to String Month
Code :
Datetime.Parse( Monvalue +"/9/2011").ToString("MMMMM")
Like :
Datetime.Parse("1/9/2011").ToString("MMMMM")
Retrun :
"January"
Before this you should handle wrong cases.I hope its help to you
As Ernest suggested, take a look at the DateTimeFormat property within System.Globalization.CultureInfo. What you're looking for is a method called GetMonthName(). The number passed into GetMonthName() is a numerical representation of that month.
static void Main(string[] args)
{
Console.WriteLine("Give me an integer between 1 and 12, and I will give you the month");
int monthInteger = int.Parse(Console.ReadLine());
DateTime newDate = new DateTime(DateTime.Now.Year, monthInteger, 1);
Console.WriteLine("The month is: " + newDate.ToString("MMMM"));
Console.WriteLine();
Console.WriteLine("Give me a month name (ex: January), and I will give you the month integer");
string monthName = Console.ReadLine();
monthInteger = DateTime.ParseExact(monthName + " 1, " + DateTime.Now.Year, "MMMM d, yyyy", System.Globalization.CultureInfo.InvariantCulture).Month;
Console.WriteLine("The month integer is " + monthInteger);
Console.ReadLine();
}
The task of translating between numbers and names is quite trivial, so how you do it depends on what kind of language elements you are currently learning.
You can divide the problem into several sub-task, like determining if the input is a number of a name, picking the right conversion based on that, and the two different ways of doing the conversion. Each sub-task can be solved in several different ways.
To examine the input you could compare it to month names, and if none of them matches assume that it's a number, or you could use Int32.TryParse to try to parse the input as a number, and if that fails assume that it's a month name.
The most basic way of doing the conversion would be a lot of if statements. You could also use a switch, use an array of month names, or use dictionaries for the separate lookups.
private string[] months = { "Jan", "Feb", "Mar", "Apr" };
public string GetMonth(int x)
{
if(x > 0 && x < months.Length)
return months[x];
else
return "";
}

Categories

Resources