Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
This program is supposed to get you a garfield comic from the date you entered or the daily comic. The first button should allow you to pick a custom comic but only the daily comic (button 2) seems to work Here's the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Garfield_Comic_Viewer
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int month = int.Parse(textBox1.Text);
int day = int.Parse(textBox2.Text);
int year = int.Parse(textBox3.Text);
switch (month)
{
case 1:
month = 01;
break;
case 2:
month = 02;
break;
case 3:
month = 03;
break;
case 4:
month = 04;
break;
case 5:
month = 05;
break;
case 6:
month = 06;
break;
case 7:
month = 07;
break;
case 8:
month = 08;
break;
case 9:
month = 09;
break;
}
switch (day)
{
case 1:
day = 01;
break;
case 2:
day = 02;
break;
case 3:
day = 03;
break;
case 4:
day = 04;
break;
case 5:
day = 05;
break;
case 6:
day = 06;
break;
case 7:
day = 07;
break;
case 8:
day = 08;
break;
case 9:
day = 09;
break;
}
pictureBox1.ImageLocation = ("http://garfield.com/uploads/strips/" +year+ "-" +month+ "-" + day + ".jpg");
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void button2_Click(object sender, EventArgs e)
{
string mon = DateTime.Now.ToString("MM");
string d = DateTime.Now.ToString("dd");
string y = DateTime.Now.ToString("yyyy");
pictureBox1.ImageLocation = "http://garfield.com/uploads/strips/" + y + "-" + mon + "-" + d + ".jpg";
DateTime whole = DateTime.Now;
}
}
}
The problem is you're expecting integers to behave like strings.
The point you're missing is that:
int a = 01;
is the same as:
int a = 1;
There's no difference. You can't pad an integer. What you need is to format the integers into a string, using a format specifier. Something like this:
pictureBox1.ImageLocation =
string.Format("http://garfield.com/uploads/strips/{0:D4}-{1:D2}-{2:D2}.jpg",
year, month, day);
This will give a string that contains the numbers in the format yyyy-mm-dd.
(The documentation for padding string-formatted integers is here.)
Related
I am having problems with putting a max number of question limit I'm new to windows forms so I tried a changing the textbox of the questions number text box to int then putting a loop using (while();) but the program just freezes + how do I tell the user answer if his answer is right or wrong using (if) didn't work for me I don't know where to put it or if my way of changing the text box to int is right here is my code.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication6
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
numrange.Items.Add("1,100");
numrange.Items.Add("1,500");
numrange.Items.Add("1,1000");
operation.Items.Add("+");
operation.Items.Add("-");
operation.Items.Add("*");
operation.Items.Add("/");
}
private void label1_Click(object sender, EventArgs e)
{
}
int[] Rand(int v)
{
Random r = new Random();
int a = r.Next(1,v);
int b = r.Next(1,v);
int[] N = { Math.Max(a,b) , Math.Min(a,b)};
return N;
}
void generate()
{
int range = 0;
switch (numrange.SelectedIndex)
{
case 0:
range = 100;
break;
case 1:
range = 500;
break;
case 2:
range = 1000 ;
break;
default :
MessageBox.Show("Please Insert a range!!");
break;
}
int[] Numbers = Rand(range);
int numofquest = Convert.ToInt32(maxquestion.Text);
int numofquestleft;
numofquestleft = numofquest;
while (numofquest > 0)
{
switch (operation.SelectedIndex)
{
case 0:
questionbox.Text = string.Format("{0} + {1} = ", Numbers[0], Numbers[1]);
break;
case 1:
questionbox.Text = string.Format("{0} - {1} = ", Numbers[0], Numbers[1]);
break;
case 2:
questionbox.Text = string.Format("{0} * {1} = ", Numbers[0], Numbers[1]);
break;
case 3:
questionbox.Text = string.Format("{0} / {1} = ", Numbers[0], Numbers[1]);
break;
default:
MessageBox.Show("Please insert an operation!!");
break;
}
numofquestleft--;
}
}
private void Startbutton1_Click(object sender, EventArgs e)
{
generate();
}
private void Nextbutton_Click(object sender, EventArgs e)
{
generate();
}
}
}
}
}
You did'nt change numofquest in the while loop, therefore numofquest > 0 is always true.
It should be while numofquestleft > 0. Be sure it;s numofquestleft and not numofquest
Aside from that, if you want to generate a different question each time you hit the button, consider putting the generate() with no loop inside the clickfunction, a loop will run all in one go. Something like this:
private int numofquestleft;
private int answer;
private void Start_Click(object sender, EventArgs e)
{
numofquestleft = Convert.ToInt32(maxquestion.Text);
if (numofquestleft > 0) generate();
numofquestleft--;
}
private void Nextbutton_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(userinput.Text) == answer){ MessageBox.Show("Correct");}
else {MessageBox.Show("Incorrect");}
if(numofquestleft > 0) generate();
numofquestleft--;
}
To check user's answer, first calculate the result:
switch(operation.SelectedIndex)
{
case 0:
questionbox.Text = string.Format("{0} + {1} = ",Numbers[0],Numbers[1]);
answer = Numbers[0] + Numbers[1];
break;
case 1:
questionbox.Text = string.Format("{0} - {1} = ",Numbers[0],Numbers[1]);
answer = Numbers[0] - Numbers[1];
break;
case 2:
questionbox.Text = string.Format("{0} * {1} = ",Numbers[0],Numbers[1]);
answer = Numbers[0] * Numbers[1];
break;
case 3:
questionbox.Text = string.Format("{0} / {1} = ",Numbers[0],Numbers[1]);
answer = Numbers[0] / Numbers[1];
break;
}
Then compare it with user input (convert to int), assuming when you hit Next:
private void Nextbutton_Click(object sender, EventArgs e)
{
if (Convert.ToInt32(userinput.Text) == answer){ MessageBox.Show("Correct");}
else {MessageBox.Show("Incorrect");}
if(numofquestleft > 0) generate();
numofquestleft--;
}
This will check the answer of a question, then generate a new question when you click Next.
So I am currently trying to finish this program that when you input a number correlating to the days of the week, it reflects the text connected to the numeric variable. (IE : Sunday - 1, Monday - 2, etc etc.)
I have found a functioning code that makes the program work, but it outputs incorrect information. No matter what number I put in, it always displays Sunday. And it doesn't stop me from inputting bad variables. Which I want it to. I'm frustrated at this point and I am very new to all of this. Can someone check over my code and tell me what I'm doing incorrectly? Thank you.
private void OkButton_Click(object sender, EventArgs e)
{
string day ="1";
int number;
if (int.TryParse(day, out number))
{
if (number >= 7 && number <= 1)
{
switch (day)
{
case "1":
dayOutputLabel.Text = "Sunday";
break;
case "2":
dayOutputLabel.Text = "Monday";
break;
case "3":
dayOutputLabel.Text = "Tuesday";
break;
case "4":
dayOutputLabel.Text = "Wednesday";
break;
case "5":
dayOutputLabel.Text = "Thursday";
break;
case "6":
dayOutputLabel.Text = "Friday";
break;
case "7":
dayOutputLabel.Text = "Saturday";
break;
}
}
else
{
MessageBox.Show("Invalid number input. Please use a number between 1 and 7.");
}
}
else
{
MessageBox.Show("Please put in a valid number.");
}
}
private void ExitButton_Click(object sender, EventArgs e)
{
this.Close();
}
Looks like you've hard coded day = "1" (i.e. Sunday).
Also this is a mistake:
if (number >= 7 && number <= 1)
Surely you meant...
if (number >= 1 && number <= 7)
I can't tell precisely what sort of project you're working on, but the following slight modification works in wpf and should be all you need to solve this:
private void OKButton_Click(object sender, RoutedEventArgs e)
{
string day = myTextBox.Text.Trim();
int number = 0;
if (int.TryParse(day, out number))
{
if (number >= 1 && number <= 7)
{
switch (day)
{
case "1":
dayOutputLabel.Content = "Sunday";
break;
case "2":
dayOutputLabel.Content = "Monday";
break;
case "3":
dayOutputLabel.Content = "Tuesday";
break;
case "4":
dayOutputLabel.Content = "Wednesday";
break;
case "5":
dayOutputLabel.Content = "Thursday";
break;
case "6":
dayOutputLabel.Content = "Friday";
break;
case "7":
dayOutputLabel.Content = "Saturday";
break;
}
}
else
{
MessageBox.Show("Invalid number input. Please use a number between 1 and 7.");
}
As mentioned in the comment above... here is a possible solution using the System.DayOfWeek enumeration:
private void OKButton_Click(object sender, RoutedEventArgs e)
{
// this TryParse makes use of pattern matching
if(int.TryParse(myTextBox.Text.Trim(), out var input) && input >= 0 && input <= 6)
{
// this should automatically convert to the name of the day of week
// if not, add .ToString() at the end
dayOutputLabel.Content = (DayOfWeek)input;
}
else
{
MessageBox.Show(
text: "Please use a number between 0 and 6",
caption: "Invalid Input",
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Error);
}
}
And here is an another option using Enum.TryParse() instead:
private void OKButton_Click(object sender, RoutedEventArgs e)
{
// this TryParse makes use of pattern matching
if(Enum.TryParse(myTextBox.Text.Trim(), out DayOfWeek input) &&
input >= DayOfWeek.Sunday && input <= DayOfWeek.Saturday)
{
// this should automatically convert to the name of the day of week
// if not, add .ToString() at the end
dayOutputLabel.Content = input;
}
else
{
MessageBox.Show(
text: "Please use a number between 0 and 6",
caption: "Invalid Input",
buttons: MessageBoxButtons.OK,
icon: MessageBoxIcon.Error);
}
}
Im trying to write a C# console program to read in the number of a month and output the name of the month, and then ask the user if they want to know the number of days in that month and if so output the number of days. Assuming that there are no leap years and February ALWAYS has 28 days only.
Thanks in advance if anyone can help!!
EDIT:
This is what I have so far, I'm having trouble with the second half of the problem, I'm not sure how to ask the user if they want to know the days of the month and how to use a switch to output the number of days...
class MainClass
{
public 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();
A simple switch case will do?
string input = Console.In.ReadLine();
int number = -1;
int.TryParse(input, out number);
switch (number)
{
case 1:
Console.Out.WriteLine("January");
break;
case 2:
Console.Out.WriteLine("February");
break;
case -1:
Console.Out.WriteLine("Please input a valid number");
break;
default:
Console.Out.WriteLine("There are only 12 months in a year");
break;
}
i take it this is enough to finish the rest of your code.
next time, please provide some code for what you have tried already, just asking for simple code usually gets you nowhere.
public static string getName(int i)
{
string[] names = { "jan", "feb", ... } // fill in the names
return names[i-1];
}
public static string getMonthName(int mounth)
{
DateTime dt = new DateTime(2000, mounth, 1);
return dt.ToString("M").Substring(0, dt.ToString("M").IndexOf(' '));
}
Based on your other related question that was closed as a duplicate of this one (https://stackoverflow.com/questions/24996241/c-sharp-number-of-days-in-a-month-using-a-switch#24996339)...
This is clearly an academic exercise that wants you to learn about the switch statement.
Here is a complete example that demonstrates a couple ways to do switch statements. Since you already grabbed the month number from the user you can switch on that value by creating a mapping between the month and the number of days in the month.
To wit:
class MainClass
{
public 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()); // WARNING: throws exception for non-integer input
Console.WriteLine(GetMonthName(monthInteger));
Console.WriteLine();
Console.Write("Display days in month (y/n)? ");
if (Console.ReadLine() == "y")
{
int daysInMonth = GetDaysInMonth_NoLeapYear(monthInteger);
if (daysInMonth > 0)
{
Console.WriteLine(String.Format("{0} days in {1}",
daysInMonth.ToString(),
GetMonthName(monthInteger)));
}
else
{
Console.WriteLine("Invalid month entered.");
}
Console.WriteLine();
}
Console.WriteLine("Hit enter to close");
Console.ReadLine();
}
private static String GetMonthName(int monthInteger)
{
DateTime newDate = new DateTime(DateTime.Now.Year, monthInteger, 1);
String monthName = newDate.ToString("MMMM");
return monthName;
}
/// <summary>
/// Prints days in month. Assumes no leap year (since no year context provided) so Feb is always 28 days.
/// </summary>
/// <param name="monthInteger"></param>
private static int GetDaysInMonth_NoLeapYear(int monthInteger)
{
int daysInMonth = -1; // -1 indicates unknown / bad value
switch (monthInteger)
{
case 1: // jan
daysInMonth = 30;
break;
case 2: // feb
daysInMonth = 28; // if leap year it would be 29, but no way of indicating leap year per problem constraints
break;
case 3: // mar
daysInMonth = 31;
break;
case 4: // apr
daysInMonth = 30;
break;
case 5: // may
daysInMonth = 31;
break;
case 6: // jun
daysInMonth = 30;
break;
case 7: // jul
daysInMonth = 31;
break;
case 8: // aug
daysInMonth = 31;
break;
case 9: // sep
daysInMonth = 30;
break;
case 10: // oct
daysInMonth = 31;
break;
case 11: // nov
daysInMonth = 30;
break;
case 12: // dec
daysInMonth = 31;
break;
}
return daysInMonth;
}
/// <summary>
/// Prints days in month. Assumes no leap year (since no year context provided) so Feb is always 28 days.
/// </summary>
/// <param name="monthInteger"></param>
private static int GetDaysInMonth_NoLeapYear_Compact(int monthInteger)
{
// uses case statement fall-through to avoid repeating yourself
int daysInMonth = -1; // -1 indicates unknown / bad value
switch (monthInteger)
{
case 2: // feb
daysInMonth = 28; // if leap year it would be 29, but no way of indicating leap year per problem constraints
break;
case 3: // mar
case 5: // may
case 7: // jul
case 8: // aug
case 10: // oct
case 12: // dec
daysInMonth = 31;
break;
case 1: // jan
case 4: // apr
case 6: // jun
case 9: // sep
case 11: // nov
daysInMonth = 30;
break;
}
return daysInMonth;
}
}
GetDaysInMonth_NoLeapYear_Compact is included only to illustrate the case fall-through behavior that lets multiple case statements go to the same code.
I am wondering if there is way to have the user enter a number like 01 and have that string converted to the month using dateTime. I know how to have the user enter a string such as 01/01/2011 and have the converted to a DateTime. Is there a way to use datetime to convert a two number string into a month. Something like this, but that would work
Console.WriteLine("Please the month numerically");
string date = Console.ReadLine();
dt = Convert.ToDateTime(date).Month;
You could probably get it jumping through some hoops with DateTime, however;
CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(int monthNumber);
is probably easier.
It is already built into the .NET framework: see System.Globalization.DateTimeFormatInfo.MonthNames
It'd be easier to just have an array of 12 elements, each being a month.
String[] Months = new String[] {"Jan", "Feb"}; //put all months in
Console.WriteLine("Please the month numerically");
string date = Console.ReadLine();
int index = 0;
if (!int.TryParse(date, out index)) {
// handle error for input not being an int
}
dt = Months[index];
If you really wanted to stick with using the DateTime class, you could take in the month and then tag on some day and year and use the method you provided in your code. For example...
dt = Convert.ToDateTime(date + "/01/2012").Month;
But this is less advised.
Your example is not complete, cause you need to specify which year and which day in the date.
Assuming that that data have to be of the current date, you can do something like this:
DateTime dt = new DateTime(DateTime.Now.Year, int.Parse("01"), DateTime.Now.Day);
Don't forget, obviously, add a couple of controls, like
Month range {1-12}
Month string is a number
EDIT
int month =-1;
if(int.TryParse(userInputString, out month)){
if(month>=1 && month <=12) {
DateTime dt = new DateTime(
DateTime.Now.Year,
month,
DateTime.Now.Day);
}
}
Hope this helps.
public static string ReturnMonthName(string pMonth)
{
switch (pMonth)
{
case "01" :
return "January";
case "02":
return "February";
case "03":
return "March";
case "04":
return "April";
case "05":
return "May";
case "06":
return "June";
case "07":
return "July";
case "08":
return "August";
case "09":
return "September";
case "10":
return "October";
case "11":
return "November";
case "12":
return "December";
default:
return "Invalid month";
}
Strip the month from your datetime and use a switch/case select to assign your variable.
switch (val)
{
case 1:
MessageBox.Show("The day is - Sunday");
break;
case 2:
MessageBox.Show("The day is - Monday");
break;
case 3:
MessageBox.Show("The day is - Tuesday");
break;
case 4:
MessageBox.Show("The day is - wednesday");
break;
case 5:
MessageBox.Show("The day is - Thursday");
break;
case 6:
MessageBox.Show("The day is - Friday");
break;
case 7:
MessageBox.Show("The day is - Saturday");
break;
default:
MessageBox.Show("Out of range !!");
break;
}
How does one go about finding the month name in C#? I don't want to write a huge switch statement or if statement on the month int. In VB.Net you can use MonthName(), but what about C#?
You can use the CultureInfo to get the month name. You can even get the short month name as well as other fun things.
I would suggestion you put these into extension methods, which will allow you to write less code later. However you can implement however you like.
Here is an example of how to do it using extension methods:
using System;
using System.Globalization;
class Program
{
static void Main()
{
Console.WriteLine(DateTime.Now.ToMonthName());
Console.WriteLine(DateTime.Now.ToShortMonthName());
Console.Read();
}
}
static class DateTimeExtensions
{
public static string ToMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(dateTime.Month);
}
public static string ToShortMonthName(this DateTime dateTime)
{
return CultureInfo.CurrentCulture.DateTimeFormat.GetAbbreviatedMonthName(dateTime.Month);
}
}
Hope this helps!
Use the "MMMM" format specifier:
string month = dateTime.ToString("MMMM");
string CurrentMonth = String.Format("{0:MMMM}", DateTime.Now)
Supposing your date is today. Hope this helps you.
DateTime dt = DateTime.Today;
string thisMonth= dt.ToString("MMMM");
Console.WriteLine(thisMonth);
If you just want to use MonthName then reference Microsoft.VisualBasic and it's in Microsoft.VisualBasic.DateAndTime
//eg. Get January
String monthName = Microsoft.VisualBasic.DateAndTime.MonthName(1);
private string MonthName(int m)
{
string res;
switch (m)
{
case 1:
res="Ene";
break;
case 2:
res = "Feb";
break;
case 3:
res = "Mar";
break;
case 4:
res = "Abr";
break;
case 5:
res = "May";
break;
case 6:
res = "Jun";
break;
case 7:
res = "Jul";
break;
case 8:
res = "Ago";
break;
case 9:
res = "Sep";
break;
case 10:
res = "Oct";
break;
case 11:
res = "Nov";
break;
case 12:
res = "Dic";
break;
default:
res = "Nulo";
break;
}
return res;
}