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 "";
}
Related
Beginner at C# and working on a Console Application currently. If I say ask the user to type in a date but they type in a string that cannot be converted to a date time how can I ensure they're requested to try again? I know this is easy via an if/else statement but if an application has hundreds of questions like this it does not seem right to have equally hundreds of if statements just to see if the datatype is correct. Is there something in built I've missed or a "hack" to carry out this?
e.g
Console.WriteLine("What is your birthday");
Datetime bday = Convert.ToDateTime(Console.ReadLine());
User enters say "dfio".
You could write a function like
public static int GetInt()
{
int X;
String Result = Console.ReadLine();
while(!Int32.TryParse(Result, out X))
{
Console.WriteLine("Not a valid Int, try again!");
Result = Console.ReadLine();
}
return X;
}
and use it multiple times.
In your case (DateTime) you only need to change the code to
public static DateTime GetDateTime()
{
DateTime X;
String Result = Console.ReadLine();
while(!DateTime.TryParse(Result, out X))
{
Console.WriteLine("Not a valid DateTime, try again!");
Result = Console.ReadLine();
}
return X;
}
bool valid = false;
DateTime bday;
while(!valid){
Console.WriteLine("What is your birthday");
string input = Console.ReadLine();
if (DateTime.TryParse(input, out bday))
{
Console.WriteLine("Invalid Date");
valid = true;
}
}
This will loop until a valid DateTime is entered.
This documentation page will help you supply a custom format to the parser.
This is only a solution to this specific input.
Use ToString() method to take input as string.
Datetime bday = Convert.ToDateTime(Console.ReadLine().ToString());
I'm trying to create a STRING in JSON format. However, one of the fields (from my editing/removing ALL spaces) now leaves a line like "START":"13/08/1410:30:00". However, I want to add a space between the date and time? I have tried using the ToCharArray() method to split the string, but I am at a loss as to how to add a space between the DATE and TIME part of the string?
For Example, i am trying to get: "START":"13/08/14 10:30:00" but instead am getting
"START":"13/08/1410:30:00"
Please note. The length of the string before the space requirement will always be 17 characters long. I am using VS 2010 for NETMF (Fez Panda II)
If the split position is always 17, then simply:
string t = s.Substring(0, 17) + " " + s.Substring(17);
Obviously you will have to sort the numbers out, but thats the general idea.
String.Format("{0} {1}", dateString.Substring(0, 17), dateString.Substring(17, dateString.Length - 17);
Or you can use the StringBuilder class:
var finalString = new StringBuilder();
for (var i = 0; i < dateString.Length; i++){
if (i == 17)
finalString.Add(" ");
else
finalString.Add(dateString.ToCharArray()[i]);
}
return finalString.ToString();
If the date time format always the same you can use string.Insert method
var output = #"""START"":""13/08/1410:30:00""".Insert(17, " ");
Strings in .Net are immutable: you can never change them. However, you can easily create a new string.
var date_time = dateString + " " + timeString;
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!
a C# program, as you see , var month is defined as int, someone said without .tostring() is better, it should remove redundant call, now it is:str= "0" + Month;
but i think it's not good .which one is better? why? thanks!(ps:my first question in stackoverflow)
string strM = string.Empty;
if ( Month < 10 )
strM = "0" + Month.ToString ( );
//strM = "0" + Month; which is better?
Use string format instead:
string strM = string.Format("{0:00}", Month);
Test:
Month: 1 => strM: "01"
Month: 12 => strM: "12"
For more string format tips check this.
The best way is to use .tostring, but not as shown.
using System;
class example {
static void Main(string[] args) {
int Month =5;
Console.WriteLine(Month.ToString("00"));
}
}
http://ideone.com/LCwca
Outputs: 05
As for your question other part, there is no difference, only clarity (style) of the code. Which to use it up to you. If you want to make an accent on that Month is not a string then you can add .ToString(). If this is obvious, like with if ( Month < 10 ), so you can see one line above comparison with int, hence Month is definetely not a string you can omit .ToString() call since it will be done automatically.
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.